I have the following dataframe:
df dataframe:
item date_buy date_sell profit window
1 shoes 2009-12-04 2021-08-14 0.22 10
2 shoes 2009-12-05 2010-09-19 1.5 10
3 shoes 2015-05-05 2020-15-15 7.3 10
4 shoes 2009-12-09 2021-08-14 0.82 4
5 shoes 2009-12-10 2010-09-20 4.5 4
6 shoes 2015-05-11 2020-15-16 1.8 4
7 hat 2009-12-04 2021-08-14 1.2 10
8 hat 2009-12-05 2010-09-19 2.25 10
9 hat 2015-05-05 2020-15-15 4.3 10
10 hat 2009-12-09 2021-08-14 3.2 4
11 hat 2009-12-10 2010-09-20 9.4 4
12 hat 2015-05-11 2020-15-16 1.8 4
What I need to do is to resample the data until today using data_buy as a key and separating the data by item and window. What I did is grouping my data by item and window, for each group I add the an extra row exactly as the last of the group changing only data_buy field with today date and then resample but the execution is extremely slow since I have several thousands of data.
this is my code:
data = data.set_index(pd.to_datetime(data ['date_buy']))
resampled_data = data.groupby(['item', 'window']).apply(lambda x: resample(x, now())
def resample(df, today):
df = pd.concat([df, df[df.index==df.index.max()].rename(index={df.index.max(): pd.to_datetime(today)})])
df = df.asfreq('B', method='ffill')
return df
the result is correct and is the following (it's similar for the item hat):
df dataframe:
item date_buy date_sell profit window
1 shoes 2009-12-04 2021-08-14 0.22 10
2 shoes 2009-12-05 2010-09-19 1.5 10
.
2 shoes 2015-05-04 2010-09-19 1.5 10
3 shoes 2015-05-05 2020-15-15 7.3 10
.
.
3 shoes 2022-09-15 2020-15-15 7.3 10
4 shoes 2009-12-09 2021-08-14 0.82 4
5 shoes 2009-12-10 2010-09-20 4.5 4
.
5 shoes 2015-05-10 2010-09-20 4.5 4
6 shoes 2015-05-11 2020-15-16 1.8 4
.
.
6 shoes 2022-09-15 2020-15-16 1.8 4
This snippet takes about 30s to execute and I wanted to make it faster. Am I missing some pandas best practice to make it faster?