如何使用groupby获取与列的最大值对应的所有行

How to get all the rows corresponding to maximum values of a column using groupby

对于给定的数据帧 df 为:

   Election Yr.  Party   States Votes
0     2000           A       a    50  
1     2000           A       b    30
2     2000           B       a    40
3     2000           B       b    50  
4     2000           C       a    30
5     2000           C       b    40
6     2005           A       a    50  
7     2005           A       b    30
8     2005           B       a    40
9     2005           B       b    50  
10    2005           C       a    30
11    2005           C       b    40

我想得到相应年份得票最多的政党。我使用以下代码对“选举年”和“政党”进行分组,然后使用 .sum() 来获得每年每个政党的总票数。

df = df.groupby(['Election Yr.', 'Party']).sum()

现在如何获得每年最高票数的派对?我无法得到这个。

非常感谢任何支持。

尝试使用 groupbyidxmax 的组合:

gb = df.groupby(["Election Yr.", "Party"]).sum()
gb.loc[gb.groupby("Election Yr.")["Votes"].idxmax()].reset_index()
>>> gb
   Election Yr. Party  Votes
0          2000     B     90
1          2005     B     90

1。使用内连接

您可以先从 df 开始,然后再进行第一个 groupby。然后你每年获得最大票数并合并年度票数组合以获得每年获得最多票数的政党。

# Original data
df = pd.DataFrame({'Election Yr.':[2000,2000,2000,2000,2000,2000,2005,2005,2005,2005,2005,2005],
                   'Party':['A','A','B','B','C','C','A','A','B','B','C','C',],
                   'Votes':[50,30,40,50,30,40,50,30,40,50,30,40]})

# Get number of votes per year-party
df = df.groupby(['Election Yr.','Party'])['Votes'].sum().reset_index()

# Get max number of votes per year
max_ = df.groupby('Election Yr.')['Votes'].max().reset_index()

# Merge on key
max_ = max_.merge(df, on=['Election Yr.','Votes'])

# Results
print(max_)

>    Election Yr.  Votes Party
> 0          2000     90     B
> 1          2005     90     B

2。排序并保持第一次观察

或者,您可以按每年的投票数排序:

df = df.groupby(['Election Yr.','Party'])['Votes'].sum().reset_index()
df = df.sort_values(['Election Yr.','Votes'], ascending=False)
print(df.groupby('Election Yr.').first().reset_index())

print(df)

>    Election Yr. Party  Votes
> 0          2000     B     90
> 1          2005     B     90

Here you can see the total number of votes given to each Party (A,B,C) according to Election Yr.