如何使用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()

现在,如何让政党每年获得最高选票?我拿不到这个。

我们非常感谢您的支持。

1。使用内部联接

在进行第一次groupby之前,您可以先从df开始。然后,你每年获得最大票数,并合并当年的选票组合,得到每年获得最多选票的政党。

# 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

尝试使用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

在这里,您可以看到根据选举年份给予每个政党(A、B、C(的总票数。

最新更新