Pandas Dataframe groupby并按max(键)过滤

时间:2022-09-27 10:37:12
td = [[10,'A'],[10, 'B'],[2, 'C']]
import pandas
df = pandas.DataFrame(td, columns['col1','col2'])
df.groupby('col1')

All, how do I get the group by the max(key). In this case 10 -> ['A','B']?

全部,我如何通过max(键)获得组。在这种情况下10 - > ['A','B']?

Thanks!

1 个解决方案

#1


0  

A generalised solution is possible via groupby to list, then using sort_index and iloc accessor:

通过groupby列表,然后使用sort_index和iloc访问器可以实现通用解决方案:

res = df.groupby('col1')['col2']\
        .apply(list)\
        .sort_index(ascending=False)

print(res.iloc[0])

['A', 'B']

#1


0  

A generalised solution is possible via groupby to list, then using sort_index and iloc accessor:

通过groupby列表,然后使用sort_index和iloc访问器可以实现通用解决方案:

res = df.groupby('col1')['col2']\
        .apply(list)\
        .sort_index(ascending=False)

print(res.iloc[0])

['A', 'B']