简体   繁体   中英

A more efficient way of repeating pandas rows for each row in another data frame?

I am pretty new to python/pandas sorry if this is a simple question. I currently have 2 dataframes, one with a date range and another with product SKUs. I want to create a data frame that repeats all SKUs for each date.

I am currently doing this by using iterrows() but it is terribly inefficient for large datasets.

Thanks in advance.

Example:

dates_df:

        Date
0 2016-01-01
1 2016-01-02
2 2016-01-03

sku_df:

  SKU
0 001
1 002
2 003

result_df:

Date          SKU
2016-01-01    001
2016-01-01    002
2016-01-01    003
2016-01-02    001
2016-01-02    002
2016-01-02    003
2016-01-03    001
2016-01-03    002
2016-01-03    003

you can use itertools.product :

In [30]: from itertools import product

In [31]: pd.DataFrame(list(product(dates.Date, sku.SKU)), columns=['Date','SKU'])
Out[31]:
        Date  SKU
0 2016-01-01  001
1 2016-01-01  002
2 2016-01-01  003
3 2016-01-02  001
4 2016-01-02  002
5 2016-01-02  003
6 2016-01-03  001
7 2016-01-03  002
8 2016-01-03  003

or using Pandas's cartesian product:

In [136]: pd.merge(dates.assign(key='x'), sku.assign(key='x'), on='key').drop('key', 1)
Out[136]:
        Date  SKU
0 2016-01-01  001
1 2016-01-01  002
2 2016-01-01  003
3 2016-01-02  001
4 2016-01-02  002
5 2016-01-02  003
6 2016-01-03  001
7 2016-01-03  002
8 2016-01-03  003

Source DFs:

In [32]: dates
Out[32]:
        Date
0 2016-01-01
1 2016-01-02
2 2016-01-03

In [33]: sku
Out[33]:
   SKU
0  001
1  002
2  003

Timing for two DFs 1K rows each, so the resulting DF will have 1M rows:

In [153]: dates = pd.DataFrame({'Date':pd.date_range('2000-01-01', periods=1000)})
     ...: sku = pd.DataFrame({'SKU':np.arange(1, 1001).astype(str)})
     ...: sku.SKU = sku.SKU.str.zfill(3)
     ...:

In [154]: dates.shape
Out[154]: (1000, 1)

In [155]: sku.shape
Out[155]: (1000, 1)

In [156]: %timeit pd.DataFrame(list(product(dates.Date, sku.SKU)), columns=['Date','SKU'])
1 loop, best of 3: 667 ms per loop

In [157]: %timeit pd.merge(dates.assign(key='x'), sku.assign(key='x'), on='key').drop('key', 1)
1 loop, best of 3: 222 ms per loop

In [158]: len(pd.DataFrame(list(product(dates.Date, sku.SKU)), columns=['Date','SKU']))
Out[158]: 1000000

In [159]: len(pd.merge(dates.assign(key='x'), sku.assign(key='x'), on='key').drop('key', 1))
Out[159]: 1000000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM