![](/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.