【问题标题】:How to calculate mean values grouped on another column in Pandas如何计算在 Pandas 的另一列上分组的平均值
【发布时间】:2015-08-09 12:22:50
【问题描述】:

对于以下数据框:

StationID  HoursAhead    BiasTemp  
SS0279           0          10
SS0279           1          20
KEOPS            0          0
KEOPS            1          5
BB               0          5
BB               1          5

我想得到类似的东西:

StationID  BiasTemp  
SS0279     15
KEOPS      2.5
BB         5

我知道我可以编写这样的脚本来获得所需的结果:

def transform_DF(old_df,col):
    list_stations = list(set(old_df['StationID'].values.tolist()))
    header = list(old_df.columns.values)
    header.remove(col)
    header_new = header
    new_df = pandas.DataFrame(columns = header_new)
    for i,station in enumerate(list_stations):
        general_results = old_df[(old_df['StationID'] == station)].describe()
        new_row = []
        for column in header_new:
            if column in ['StationID']: 
                new_row.append(station)
                continue
            new_row.append(general_results[column]['mean'])
        new_df.loc[i] = new_row
    return new_df

但我想知道 pandas 中是否有更直接的东西。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这就是groupby 的用途:

    In [117]:
    df.groupby('StationID')['BiasTemp'].mean()
    
    Out[117]:
    StationID
    BB         5.0
    KEOPS      2.5
    SS0279    15.0
    Name: BiasTemp, dtype: float64
    

    这里我们按“StationID”列分组,然后访问“BiasTemp”列并在其上调用mean

    docs 中有一个关于此功能的部分。

    【讨论】:

      【解决方案2】:

      您可以在StationID 上使用groupby,然后在BiasTemp 上使用mean()。要输出Dataframe,请使用as_index=False

      In [4]: df.groupby('StationID', as_index=False)['BiasTemp'].mean()
      Out[4]:
        StationID  BiasTemp
      0        BB       5.0
      1     KEOPS       2.5
      2    SS0279      15.0
      

      没有as_index=False,它会返回一个Series

      In [5]: df.groupby('StationID')['BiasTemp'].mean()
      Out[5]:
      StationID
      BB            5.0
      KEOPS         2.5
      SS0279       15.0
      Name: BiasTemp, dtype: float64
      

      在此 pydata tutorial 中了解有关 groupby 的更多信息。

      【讨论】:

      • 这与 .transform(numpy.mean).apply(numpy.mean) 之类的操作有何不同?
      【解决方案3】:

      可以这样做:

      df.groupby('StationID').mean()
      

      【讨论】:

        猜你喜欢
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-02
        • 1970-01-01
        • 2015-07-22
        • 2021-08-19
        相关资源
        最近更新 更多