从计算基准日的天数n平均

问题描述 投票:1回答:1

我想计算的,因为当时有在产品规格的任何改变日期的产品最近5天销售的平均水平。

我的2个dataframes的;

DF1:

Products Change date
X        10/12/2018
Y        06/12/2018

DF2:

enter image description here

期望的输出是:

Product  Average of last 5 days before change

X        37.6
Y        6
python pandas
1个回答
0
投票

首先,你需要使用熊猫rolling function来计算你的后五期平均值。然后,因为你有你的参考日期在另一个数据帧需要一个连接,BROTHER。

# calculate rolling 5 period average for all dates
df2 = df2.set_index(['Date','Product'])
df2['ROLLING_AVERAGE_SALES'] = df2.rolling(5).mean()
df2 = df2.reset_index(drop = False)

# Now let's isolate the change dates by joining in the other table
df1['IS_CHANGE_DATE'] = True
df3 = df2.merge(df1, left_on = ['Product','Date'],right_on = ['Products','Change Date'], how ='left')

result_df = df3[df3.IS_CHANGE_DATE == True]


# Yeeeeeee boy
print(result_df)

这是未经测试,但它表明你的方法。和亲爱的上帝,为人类的缘故...重命名列完全相同的事情,所以他们是一致的。

© www.soinside.com 2019 - 2024. All rights reserved.