pandas 按第一列值分组并找到剩余列的最大值

pandas group by first column values and find maximum of remaining columns

我有一个 pandas 数据框

import pandas as pd
  
country = ['US', 'US', 'US', 'UK', 'UK', 'Canada', 'Canada', "Mexico"]
rating =  [0, 2, 1, 4, 3, 1, 0, 1]
count = [1, 2, 3, 1, 2, 1, 2, 1]  

df = pd.DataFrame(list(zip(country,rating, count)), columns =['country', 'rating', 'count'])

结果为以下数据帧

    country rating  count
0   US         0    1
1   US         2    2
2   US         1    3
3   UK         4    1
4   UK         3    2
5   Canada     1    1
6   Canada     0    2
7   Mexico     1    1

我想做的是按第一列的值分组,然后为各个组找到第二列和第三列的最大值。所以输出数据帧如下:

    country rating  count
0   US         2    3
1   UK         4    2
2   Canada     1    2
3   Mexico     1    1

您可以使用groupby函数。

df.groupby(['country']).max()
         rating  count
country               
Canada        1      2
Mexico        1      1
UK            4      2
US            2      3

如果您希望您的索引不是国家名称,您可以重新设置它。

new_df = df.groupby(['country']).max()
new_df.reset_index(inplace=True)
  country  rating  count
0  Canada       1      2
1  Mexico       1      1
2      UK       4      2
3      US       2      3

编辑

感谢@Henry Ecker指出,没有国名索引的grupby可以通过以下行获取:

df.groupby(['country'], as_index=False).max()

使用DataFrame.groupby and GroupBy.max

df.groupby("country").max()
         rating  count
country
Canada        1      2
Mexico        1      1
UK            4      2
US            2      3

使用 groupbyagg 保留每列的最大值:

>>> df.groupby('country').agg({'rating': max, 'count': max}).reset_index()

  country  rating  count
0  Canada       1      2
1  Mexico       1      1
2      UK       4      2
3      US       2      3

我的答案比其他答案更一般,因为如果你想要一列的最大值和另一列的最小值,你可以 agg.