【问题标题】:Find annual average of pandas dataframe with date column使用日期列查找熊猫数据框的年平均值
【发布时间】:2017-07-20 04:49:53
【问题描述】:
        id      vi       dates     f_id
0  5532714  0.549501  2015-07-07    ff_22
1  5532715  0.540969  2015-07-08    ff_22
2  5532716  0.531477  2015-07-09    ff_22
3  5532717  0.521029  2015-07-10    ff_22
4  5532718  0.509694  2015-07-11    ff_22

在上面的数据框中,我想找到每年的平均年值。这不起作用:

df.groupby(df.dates.year)['vi'].transform(mean)

我收到此错误:*** AttributeError: 'Series' object has no attribute 'year' 如何解决这个问题?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    让我们确保日期是 datetime dtype,然后使用 .dt 访问器作为 .dt.year

    df['dates'] = pd.to_datetime(df.dates)
    df.groupby(df.dates.dt.year)['vi'].transform('mean')
    

    输出:

    0    0.530534
    1    0.530534
    2    0.530534
    3    0.530534
    4    0.530534
    Name: vi, dtype: float64
    

    【讨论】:

      【解决方案2】:

      使用Grouper 函数而不是已弃用的TimeGrouper,更新并完成下面@piRsquared 的示例以获取最新版本的pandas(例如v1.1.0):

      import pandas as pd
      import numpy as np
      tidx = pd.date_range('2010-01-01', '2013-12-31', name='dates')
      np.random.seed([3,1415])
      df = pd.DataFrame(dict(vi=np.random.rand(tidx.size)), tidx)
      df.groupby(pd.Grouper(freq='1Y')).mean()
      

      【讨论】:

        【解决方案3】:

        您也可以使用pd.TimeGrouper,频率为A

        考虑由四年的每日数据组成的数据框df

        tidx = pd.date_range('2010-01-01', '2013-12-31', name='dates')
        
        np.random.seed([3,1415])
        df = pd.DataFrame(dict(vi=np.random.rand(tidx.size)), tidx)
        

        df.groupby(pd.TimeGrouper('A')).mean()
        
                          vi
        dates               
        2010-12-31  0.465121
        2011-12-31  0.511640
        2012-12-31  0.491363
        2013-12-31  0.516614
        

        【讨论】:

        • 对于那些使用最新版本的 pandas 的用户,不推荐使用 TimeGrouper。
        猜你喜欢
        • 1970-01-01
        • 2018-08-29
        • 2021-03-10
        • 2021-09-25
        • 2018-11-16
        • 2016-03-03
        • 2015-01-21
        • 2018-05-15
        • 2021-04-20
        相关资源
        最近更新 更多