python - pandas如何计算昨天的数据并用在今天的数据计算中?

标签 python pandas

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/

相关文章:

python - 如何从字典中删除重复值?

python - 循环遍历 2 个 Pandas Dataframes 并将行值传递给计算距离的函数

python - 当有多个规范时,在 Pandas 中优化计算的最佳做法是什么?

python - 过滤 Pandas 数据框列中的字符串/ float /整数值

python - PIL/JPEG 库 : "decoder jpeg not available"

python - 如何将 httpie 与 httpie-aws-authv4 捆绑到 Python zipapp 中?

python - 使用Python中的线性回归估算缺失值

python - 过滤掉pandas数据框中的重复数据

python - 训练 tf.estimator 时记录准确度指标

python - 运行时间太长