简体   繁体   English

在 groupby 之后计算组中的最小值和最大值之间的差异

[英]Calculate difference between min and max values in a group after a groupby

Based on the df (test) below I calculate the mean of each group ('col1', 'col2').根据下面的 df(测试),我计算每组的平均值('col1','col2')。 After that, I would like to perform a new groupby using only 'col1' and calculate the difference between min and max values of the column 'mean', created by the first groupby.之后,我想只使用'col1'执行一个新的groupby,并计算由第一个groupby创建的'mean'列的最小值和最大值之间的差异。

How can this be done in an elegant way?如何以优雅的方式做到这一点?

test=pd.DataFrame({'col1':['B', 'A', 'A', 'B', 'B', 'C', 'C', 'A', 'A', 'B', 'B', 'C', 'C', 'B', 'C', 'C', 'A'],
             'col2':['W', 'L', 'W', 'L', 'W', 'L', 'L', 'L', 'W', 'L', 'W', 'L', 'L', 'W', 'W', 'L', 'L'],
             'value':[32,54,65,24,54,39,76,51,21,4,46,73,59,23, 43,23,12]})

print(test.groupby(['col1', 'col2'])[['value']].agg(
    n=('value', 'count'),
    mean=('value', 'mean')))

You can aggregate using thenumpy.ptp method:您可以使用numpy.ptp方法进行聚合:

(test.groupby(['col1', 'col2'])[['value']]
     .agg(n=('value', 'count'), # this is now useless
          mean=('value', 'mean'))
     .groupby('col1').agg(diff=('mean', np.ptp))
)

Alternative: use lambda g: g.max()-g.min() as aggregation function.替代方案:使用lambda g: g.max()-g.min()作为聚合 function。

Output: Output:

       diff
col1       
A      4.00
B     24.75
C     11.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM