【问题标题】:How to apply rolling mean function while keeping all the observations with duplicated indices in time如何应用滚动平均函数,同时及时保持所有具有重复索引的观测值
【发布时间】:2021-12-25 15:44:47
【问题描述】:

我有一个具有重复时间索引的数据框,我想获得前 2 天的平均值(我不想放弃任何观察;它们都是我需要的信息)。我检查了 pandas 文档并阅读了 Stackoverflow 上的先前帖子(例如 Apply rolling mean function on data frames with duplicated indices in pandas),但找不到解决方案。这是我的数据框的外观和我正在寻找的输出的示例。提前谢谢你。

数据:

import pandas as pd
df = pd.DataFrame({'id': [1,1,1,2,3,3,4,4,4],'t': [1, 2, 3, 2, 1, 2, 2, 3, 4],'v1':[1, 2, 3, 4, 5, 6, 7, 8, 9]})

输出:

t v2
1 -
2 -
3 4.167
4 5
5 6.667

【问题讨论】:

    标签: python pandas rolling-computation


    【解决方案1】:

    感谢您的所有帮助。我最终使用 groupby + rolling(2 天),然后删除重复项(保留最后一次观察)。

    【讨论】:

      【解决方案2】:

      连接输入帧的 2 个副本的粗略建议,其中 't' 中的值分别替换为 't+1' 和 't+2' 的值。这样,“t”列的含义就变成了“目标日期”。

      设置:

      import pandas as pd
      df = pd.DataFrame({'id': [1,1,1,2,3,3,4,4,4],
                         't': [1, 2, 3, 2, 1, 2, 2, 3, 4],
                         'v1':[1, 2, 3, 4, 5, 6, 7, 8, 9]})
      

      实施:

      len = df.shape[0]
      incr = pd.DataFrame({'id': [0]*len, 't': [1]*len, 'v1':[0]*len}) # +1 in 't'
      df2 = pd.concat([df + incr, df + incr + incr]).groupby('t').mean()
      df2 = df2[1:-1] # Drop the days that have no full values for the 2 previous days 
      df2 = df2.rename(columns={'v1': 'v2'}).drop('id', axis=1)
      

      输出:

               v2 
      t          
      3  4.166667 
      4  5.000000 
      5  6.666667 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-23
        • 2017-06-14
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多