![](/img/trans.png)
[英]get the difference between max and min for a groupby in pandas and calculate the average
[英]Calculate difference between min and max values in a group after a groupby
根据下面的 df(测试),我计算每组的平均值('col1','col2')。 之后,我想只使用'col1'执行一个新的groupby,并计算由第一个groupby创建的'mean'列的最小值和最大值之间的差异。
如何以优雅的方式做到这一点?
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')))
您可以使用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))
)
替代方案:使用lambda g: g.max()-g.min()
作为聚合 function。
Output:
diff
col1
A 4.00
B 24.75
C 11.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.