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

2024-06-16 08:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

对于给定的数据帧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()

现在,如何让该党获得每年最多的选票?我拿不到这个

非常感谢您的支持


Tags: 数据代码dfpartysum年份groupby选票
3条回答

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

一,。使用内部联接

你可以先从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

二,。排序和保留首次观察

或者,您可以每年按投票进行排序:

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

相关问题 更多 >