This is my df: ts 是时间戳,索引。 x1 是值
x1
ts
2017-09-01 17:22:42 7.0
2017-09-01 17:22:53 11.0
2017-09-01 17:23:04 9.0
2017-09-02 17:23:15 15.0
2017-09-03 17:23:26 13.0
2017-09-03 17:23:38 19.0
2017-09-03 17:23:49 13.0
2017-09-04 17:24:00 15.0
我想要一列值等于昨天的平均值 + 今天的平均值:
x1 result
ts
2017-09-01 17:22:42 7.0 (7+11+9) /3
2017-09-01 17:22:53 11.0 (7+11+9) /3
2017-09-01 17:23:04 9.0 (7+11+9) /3
2017-09-02 17:23:15 15.0 (7+11+9) /3 + 15/1
2017-09-03 17:23:26 13.0 15/1 + (13+19+13)/3
2017-09-03 17:23:38 19.0 15/1 + (13+19+13)/3
2017-09-03 17:23:49 13.0 15/1 + (13+19+13)/3
2017-09-04 17:24:00 15.0 15/1 + (13+19+13)/3
如果没有昨天的数据则使用0
最佳答案
使用pd.merge_asof
, pd.DataFrame.resample
, 和 pd.DataFrame.rolling
pd.merge_asof(
df,
df.resample('D').mean().rolling(2, 1).sum().rename(columns={'x1': 'result'}),
left_index=True, right_index=True
)
x1 result
ts
2017-09-01 17:22:42 7.0 9.0
2017-09-01 17:22:53 11.0 9.0
2017-09-01 17:23:04 9.0 9.0
2017-09-02 17:23:15 15.0 24.0
2017-09-03 17:23:26 13.0 30.0
2017-09-03 17:23:38 19.0 30.0
2017-09-03 17:23:49 13.0 30.0
2017-09-04 17:24:00 15.0 30.0
关于python - pandas如何计算昨天的数据并用在今天的数据计算中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46437424/