【问题标题】:Group by 'Date' while calculating average on other column在计算其他列的平均值时按“日期”分组
【发布时间】:2017-05-02 20:37:15
【问题描述】:

我有一个包含 3 列的数据框:ID、日期、Data_Value 报告来自不同气象站 (ID) 的给定时间段(日期 - 每天)内的每日温度记录 (Data_Value)。我需要的是每天“分组”并计算每天的平均温度,例如

ID      |   Date       | Data_Value
------------------------------------
12345   |   02-05-2017 |  22
12346   |   02-05-2017 |  24
12347   |   02-05-2017 |  20
12348   |   01-05-2017 |  18
12349   |   01-05-2017 |  16

变成:

ID      |   Date       | Data_Value
------------------------------------
.....   |   02-05-2017 | 22
.....   |   01-05-2017 | 17

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我认为你需要groupby 和聚合mean

    df = df.groupby('Date', as_index=False, sort=False)['Data_Value'].mean()
    print (df)
             Date  Data_Value
    0  02-05-2017          22
    1  01-05-2017          17
    

    然后如果需要还 ID 值使用 agg:

    df = df.groupby('Date', as_index=False, sort=False)
           .agg({'Data_Value':'mean', 'ID':lambda x: ','.join(x.astype(str))})
           .reindex_axis(['ID','Date','Data_Value'], axis=1)
    print (df)
                      ID        Date  Data_Value
    0  12345,12346,12347  02-05-2017          22
    1        12348,12349  01-05-2017          17
    

    或者如果只有ID 的第一个值由first 聚合:

    df = df.groupby('Date', as_index=False, sort=False) 
           .agg({'Data_Value':'mean', 'ID':'first'}) 
           .reindex_axis(['ID','Date','Data_Value'], axis=1)
    print (df)
    
          ID        Date  Data_Value
    0  12345  02-05-2017          22
    1  12348  01-05-2017          17
    

    【讨论】:

    • 这很好用,没那么难……非常感谢!
    猜你喜欢
    • 2021-07-09
    • 2014-06-04
    • 1970-01-01
    • 2014-12-28
    • 2020-07-24
    • 2018-06-23
    • 2010-10-30
    • 2021-07-07
    • 2014-11-04
    相关资源
    最近更新 更多