简体   繁体   English

Pandas Groupby 最多多列

[英]Pandas Groupby Max of Multiple Columns

Given this data frame:给定这个数据框:

import pandas as pd
df = pd.DataFrame({'group':['a','a','b','c','c'],'strings':['ab','   ','   ','12','  '],'floats':[7.0,8.0,9.0,10.0,11.0]})

    group strings  floats
0     a      ab     7.0
1     a             8.0
2     b             9.0
3     c      12    10.0
4     c            11.0

I want to group by "group" and get the max value of strings and floats.我想按“组”分组并获得字符串和浮点数的最大值。

Desired result:期望的结果:

      strings  floats
group                
a          ab     8.0
b                 9.0
c          12    11.0

I know I can just do this:我知道我可以这样做:

df.groupby(['group'], sort=False)['strings','floats'].max()

But in reality, I have many columns so I want to refer to all columns (save for "group") in one go.但实际上,我有很多列,所以我想引用一个 go 中的所有列(“组”除外)。

I wish I could just do this:我希望我可以这样做:

df.groupby(['group'], sort=False)[x for x in df.columns if x != 'group'].max()

But, alas, "invalid syntax".但是,唉,“无效的语法”。

If need max of all columns without group is possible use:如果需要没有group的所有列的max ,可以使用:

df = df.groupby('group', sort=False).max()
print (df)
      strings  floats
group                
a          ab     8.0
b                 9.0
c          12    11.0

Your second solution working if add next [] :如果添加 next [] ,您的第二个解决方案将起作用:

df = df.groupby(['group'], sort=False)[[x for x in df.columns if x != 'group']].max()
print (df)
      strings  floats
group                
a          ab     8.0
b                 9.0
c          12    11.0

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

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