加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – pandas如何计算昨天的数据并在今天的数据计算中使用它

发布时间:2020-12-20 12:03:42 所属栏目:Python 来源:网络整理
导读:这是我的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
这是我的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.resamplepd.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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读