gpt4 book ai didi

python - 计算自引用日期起 n 天的平均值

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:13 24 4
gpt4 key购买 nike

我想计算自产品规范发生任何变化之日起最近 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

最佳答案

首先,你需要使用 pandas rolling 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)

这尚未经过测试,但它向您展示了方法。亲爱的主啊,为了人类的缘故...将您的列重命名为完全相同的名称,以便它们保持一致。

关于python - 计算自引用日期起 n 天的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com