【问题标题】:Apply rolling mean function on data frames with duplicated indices in pandas在 pandas 中具有重复索引的数据帧上应用滚动平均函数
【发布时间】:2015-04-23 11:27:40
【问题描述】:

我很难在以下包含重复索引的数据框中使用 pd.rolling_mean 函数:

               amount
    20140101    3
    20140102    4
    20140103    3
    20140103    5
    20140103    1
    20140104    5
    20140105    6
    20140106    2
    …

我需要计算“金额”的3天平均值,例如2014010120140103的平均值应该是(3+4+3+5+1)/5=3.2,20140104到20140106的平均值应该是(5+6+2)/3=4.3

有人知道怎么做吗?提前谢谢!

【问题讨论】:

    标签: python numpy pandas dataframe average-precision


    【解决方案1】:

    如果您的日期列已经是日期时间并且是索引,您可以调用rolling_mean

    In [15]:
    
    pd.rolling_mean(df['amount'], window=1,  freq='3d')
    Out[15]:
    date
    2014-01-01    3.200000
    2014-01-04    4.333333
    Freq: 3D, dtype: float64
    

    如果需要,您可以通过执行以下操作将索引转换为日期时间:

    df.index = pd.to_datetime(df.index.astype(str), '%Y%m%d')

    这是在索引实际上是 dtype int64 的情况下,如果它已经是一个字符串,那么你可以忽略 astype

    【讨论】:

    • 直到现在才意识到'freq'的用法,谢谢!它不适用于空间不规则的数据帧,而我的实际数据帧就是这种情况。
    【解决方案2】:

    你可以这样做:

    >>> df
              amount
    20140101       3
    20140102       4
    20140103       3
    20140103       5
    20140103       1
    20140104       5
    20140105       6
    20140106       2
    >>> xf = df.groupby(level=0)['amount'].agg(['sum', 'count'])
    >>> xf
              sum  count
    20140101    3      1
    20140102    4      1
    20140103    9      3
    20140104    5      1
    20140105    6      1
    20140106    2      1
    >>> pd.rolling_sum(xf['sum'], 3, 0) / pd.rolling_sum(xf['count'], 3, 0)
    20140101    3.000
    20140102    3.500
    20140103    3.200
    20140104    3.600
    20140105    4.000
    20140106    4.333
    dtype: float64
    

    你会得到3.24.3,分别对应2014010320140106

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-21
      • 2021-12-25
      • 2018-12-18
      • 2018-07-05
      • 2015-07-26
      • 2020-10-30
      • 2015-02-10
      • 1970-01-01
      相关资源
      最近更新 更多