【问题标题】:Python/Pandas - Combining groupby mean and minPython/Pandas - 结合 groupby 平均值和最小值
【发布时间】:2017-08-05 20:56:18
【问题描述】:

在数据帧上组合 mean 和 min 的语法是什么?我想按 2 列分组,计算 col3 的组内平均值并保持 col4 的 min 值。像

groupeddf = nongrouped.groupby(['col1', 'col2', 'col3'], as_index=False).mean().min('col4')

工作?如果不是,正确的语法是什么?谢谢!

编辑

好的,所以如果没有示例,这个问题就不太清楚了。我现在会更新它。上面的文字也有变化。

我有:

ungrouped
col1 col2 col3 col4
1    2    3    4
1    2    4    1
2    4    2    1
2    4    1    3
2    3    1    3

想要的输出按第 1-2 列、第 3 列的平均值(实际上是数据上的更多列,这是简化的)和 col4 的最小值:

grouped
col1 col2 col3 col4
1    2    3.5  1
2    4    1.5  1
2    3    1    3

【问题讨论】:

    标签: python pandas group-by mean min


    【解决方案1】:

    我认为您首先需要mean,然后是col4 列的min:

    min_val = nongrouped.groupby(['col1', 'col2', 'col3'], as_index=False).mean()['col4'].min()
    

    或Series中的min:

    min_val = nongrouped.groupby(['col1', 'col2', 'col3'])['col4'].mean().min()
    

    示例:

    nongrouped = pd.DataFrame({'col1':[1,1,3],
                       'col2':[1,1,6],
                       'col3':[1,1,9],
                       'col4':[1,3,5]})
    
    print (nongrouped)
       col1  col2  col3  col4
    0     1     1     1     1
    1     1     1     1     3
    2     3     6     9     5
    
    print (nongrouped.groupby(['col1', 'col2', 'col3'])['col4'].mean())
    1     1     1       2
    3     6     9       5
    Name: col4, dtype: int64
    
    min_val = nongrouped.groupby(['col1', 'col2', 'col3'])['col4'].mean().min()
    print (min_val)
    2
    

    编辑:

    你需要aggregate:

    groupeddf = nongrouped.groupby(['col1', 'col2'], sort=False)
                          .agg({'col3':'mean','col4':'min'})
                          .reset_index()
                          .reindex(columns=nongrouped.columns)
    print (groupeddf)
       col1  col2  col3  col4
    0     1     2   3.5     1
    1     2     4   1.5     1
    2     2     3   1.0     3
    

    【讨论】:

    • 是的,如果有一些样本有问题会更好。
    • 差不多 100k! :D
    • 这是我的命名日礼物,因为我的名字是乔;)
    • 是的,我也觉得 ;)
    • 我们开始了!恭喜!
    猜你喜欢
    • 2017-04-23
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多