从参考d计算n个天数的平均值

2024-10-01 07:38:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算自产品规格发生任何变化之日起最近5天内产品的平均销售量

我的2个数据帧是

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

Tags: of数据date产品productchangedaysproducts
1条回答
网友
1楼 · 发布于 2024-10-01 07:38:41

首先,您需要使用pandasrolling function来计算您的尾随五个周期的平均值。然后,因为你的参考日期在另一个数据框中,你需要一个连接,兄弟

# 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)

这是未经测试的,但它向您展示了方法。亲爱的上帝,为了人类。。。将列重命名为完全相同的名称,以便它们保持一致

相关问题 更多 >