【问题标题】:Python pandas groupby agg- sum one column while getting the mean of the restPython pandas groupby 聚合一列,同时获取其余列的平均值
【发布时间】:2020-03-20 01:52:00
【问题描述】:

希望根据日期对我的字段进行分组,并获得除二进制列之外的所有列的平均值,我想对它求和以获得计数。

我知道我可以这样做:

newdf=df.groupby('date').agg({'var_a': 'mean', 'var_b': 'mean', 'var_c': 'mean', 'binary_var':'sum'})

但是我想要表示大约 50 列(二进制除外),我觉得必须有一种简单、更快的方法来执行此操作,而不是为所有他们。我试图制作一个列名列表,但是当我把它放在 agg 函数中时,它说列表是一种不可散列的类型。

谢谢!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这样的事情可能会奏效 -

    df = pd.DataFrame({'a':['a','a','b','b','b','b'], 'b':[10,20,30,40,20,10], 'c':[1,1,0,0,0,1]}, 'd':[20,30,10,15,34,10])
    df 
       a   b  c   d
    0  a  10  1  20
    1  a  20  1  30
    2  b  30  0  10
    3  b  40  0  15
    4  b  20  0  34
    5  b  10  1  10
    

    假设c 是二进制变量列。那么,

    cols = [ val for val in df.columns if val != 'c']
    temp = pd.concat([df.groupby(['a'])[cols].mean(), df.groupby(['a'])['c'].sum()], axis=1).reset_index()
    temp 
       a     b      d  c
    0  a  15.0  25.00  2
    1  b  25.0  17.25  1
    

    【讨论】:

      【解决方案2】:

      一般来说,我会自动构建 agg dict:

      sum_cols = ['binary_val']
      agg_dict = {col: 'sum' if col in sum_cols else 'mean'
                     for col in df.columns if col != 'date'}
      
      df.groupby('date').agg(agg_dict)
      

      【讨论】:

      • 嗨,谢谢!这是有道理的,但不幸的是它引发了数据错误-DataError: No numeric types to aggregate
      猜你喜欢
      • 1970-01-01
      • 2021-10-20
      • 2018-11-17
      • 2018-03-01
      • 2021-04-07
      • 2018-08-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多