【问题标题】:How to create multiple summary statistics for each column in a grouping?如何为分组中的每一列创建多个汇总统计信息?
【发布时间】:2021-09-27 13:36:39
【问题描述】:

使用 groupby().agg() 可以计算特定命名列的汇总统计信息。但是,如果我想为每组数据帧的每一列计算“min”、“max”和“mean”怎么办。有没有办法让熊猫自动为每个列名附加前缀?我不想在 agg() 函数中枚举每个基本列名。

【问题讨论】:

    标签: python pandas grouping


    【解决方案1】:

    您可以遍历每一列,然后使用原始列名作为起点创建前缀等。如果您使用 .agg 并在同一列上执行 min 和 max ,那么据我所知,您只会得到最后一个操作,尽管也许有办法做到这一点。所以在这个例子中,我一次只做一个操作。这是一种做你想做的事情的方法,假设有一个特定的列 'col1' 用于排列所有 groupby 数据。:

    df = pd.DataFrame({'col1': ['A', 'A', 'B', 'B'], 'col2': [1, 2, 3, 4], 'col3': [5, 6, 7, 8]})
    
    col_list = df.columns.tolist()
    col_list.remove('col1')  # the column you will use for the groupby output
    dfg_all = df[['col1']].drop_duplicates()
    
    for col in col_list:
        for op in ['min', 'max', 'mean']:
            if op == 'min':
                dfg = df.groupby('col1', as_index=False)[col].min()
            elif op == 'max':
                dfg = df.groupby('col1', as_index=False)[col].max()
            else:
                dfg = df.groupby('col1', as_index=False)[col].mean()
            dfg = dfg.rename(columns={col:col+'_'+ op})
            dfg_all = dfg_all.merge(dfg, on='col1', how='left')
    

    得到

      col1  col2_min  col2_max  col2_mean  col3_min  col3_max  col3_mean
    0    A         1         2        1.5         5         6        5.5
    1    B         3         4        3.5         7         8        7.5
    

    【讨论】:

      【解决方案2】:

      您可以使用describe(): 到达那里

      df1 = pd.DataFrame(df.describe().unstack())
      n_label = pd.Series(['_'.join(map(str,i)) for i in df1.index.tolist()])
      df1 = df1.reset_index(drop=True)
      df1['label'] = n_label
      print(df1[df1['label'].str.contains('_m')].reset_index(drop=True))
      
               0      label
      0   4.0105  col1_mean
      1   0.0000   col1_min
      2  12.0000   col1_max
      3   3.9639  col2_mean
      4   0.0000   col2_min
      5  12.0000   col2_max
      6   4.0256  col3_mean
      7   0.0000   col3_min
      8  12.0000   col3_max
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 2019-03-19
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-08
        相关资源
        最近更新 更多