python - 获取 Pandas 的月平均值

标签 python pandas dataframe datetime

我有以下时间序列:

        Date        Value
0       2006-01-03  18
1       2006-01-04  12
2       2006-01-05  11
3       2006-01-06  10
4       2006-01-09  22
...     ...     ...
3510    2019-12-23  47
3511    2019-12-24  46
3512    2019-12-26  35
3513    2019-12-27  35
3514    2019-12-30  28
我想计算每月的平均值。所以每个月的伪代码如下:
  • 将该月中每一天的所有值相加
  • 除以该月数据的天数。

  • 所需的输出类似于:
            Date        Value
    0       2006-01     17.45
    1       2006-02     18.23
    2       2006-04     16.79
    3       2006-05     17.98
    ...     ...     ...
    166     2019-11     37.89
    167     2019-12     36.34
    
    我试过这个没有成功:
    data = data.set_index('Date')
    data.resample('M')
    
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-28-435afe449f1f> in <module>
         47 data = pd.DataFrame(dataList, columns=('Date', 'Value'))
         48 data = data.set_index('Date')
    ---> 49 data.resample('M')
    

    最佳答案

    我们可以将您的日期时间列转换为 PeriodIndex在每月频率上,然后使用 GroupBy.mean 取平均值:

    df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['Value'].mean()
        
    Date
    2006-01    14.6
    2019-12    38.2
    Freq: M, Name: Value, dtype: float64
    
    df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['Value'].mean().reset_index()
    
          Date  Value
    0  2006-01   14.6
    1  2019-12   38.2
    
    这种方法的一个警告是没有显示缺失的月份。如果这很重要,请使用 set_indexresample.mean以同样的方式。

    关于python - 获取 Pandas 的月平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65471540/

    相关文章:

    python - pandas:将日期时间转换为月末

    python - 正则表达式:替换文本,除非它位于引号之间

    python - 当我在构建机器人时尝试包含登录按钮的 HTML 详细信息时,收到 "NoSuchElementException"

    python - 更改一个数据框也会更改其副本

    python - 查找匹配 2 列条件的单个数据帧行索引

    python - 如何使用 apply 两个 pandas 列(包括列表)来使用另一列中的元素返回一列列表中的索引?

    python - 在 Python 中定义梯度和 hessian 函数

    python - 如何在 Pandas 中放置 2 个不同的数据框

    python - Pandas 数据框在枢轴后 reshape

    python - 操作/重新编码 Pandas 数据框