pandas 聚合-如何保留所有列 [英] Pandas aggregate -- how to retain all columns
本文介绍了 pandas 聚合-如何保留所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例数据帧:
rand = np.random.RandomState(1)
df = pd.DataFrame({'A': ['group1', 'group2', 'group3'] * 2,
'B': rand.rand(6),
'C': rand.rand(6),
'D': rand.rand(6)})
print df
A B C D
0 group1 0.417022 0.186260 0.204452
1 group2 0.720324 0.345561 0.878117
2 group3 0.000114 0.396767 0.027388
3 group1 0.302333 0.538817 0.670468
4 group2 0.146756 0.419195 0.417305
5 group3 0.092339 0.685220 0.558690
Groupby列A
Groupby column A
group = df.groupby('A')
使用agg返回每个组的最大值
Use agg to return max value for each group
max1 = group['B'].agg({'max' : np.max})
print max1
max
A
group1 0.417022
group2 0.720324
group3 0.092339
但我想保留(或取回)适当的数据在其他列C和D中。这将是包含最大值的行的剩余数据。
因此,返回值应为:
But I would like to retain (or get back) the appropriate data in the other columns, C and D. This would be the remaining data for the row which contained the max value. So, the return should be:
A B C D
group1 0.417022 0.186260 0.204452
group2 0.720324 0.345561 0.878117
group3 0.092339 0.685220 0.558690
有人可以显示如何执行此操作吗?
Can anybody show how to do this? Any help appreciated.
推荐答案
两个阶段:首先查找索引,然后查找所有行。
Two stages: first find indices, then lookup all the rows.
idx = df.groupby('A').apply(lambda x: x['B'].argmax())
idx
Out[362]:
A
group1 0
group2 1
group3 5
df.loc[idx]
Out[364]:
A B C D
0 group1 0.417022 0.186260 0.204452
1 group2 0.720324 0.345561 0.878117
5 group3 0.092339 0.685220 0.558690
这篇关于 pandas 聚合-如何保留所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文