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

标签 python pandas

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

相关文章:

python - 使用 where 子句中的变量从 sqlite3 读取 pandas 数据帧

python - 使用 python "re"获取子字符串的位置

python - 如何检查子进程的 Popen 是否抛出错误

python - 多行 jsons 的 pandas read_json 返回 JSONReader 而不是数据帧

python - Pandas 有条件地交换两列中的值

python - pandas 数据框的条件合并

python - 如何在 Pandas 中创建多级数据框?

java - 在 Java 中集成 Python 脚本

python - 使用 applescript (重新)启动 python 脚本

python - 不能 "activate"virtualenv