【问题标题】:How to get all the rows corresponding to maximum values of a column using groupby如何使用groupby获取与列最大值对应的所有行
【发布时间】:2021-08-26 11:47:34
【问题描述】:

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

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

非常感谢任何支持。

【问题讨论】:

  • 我认为您正在寻找这个答案中的 idmax 解决方案:stackoverflow.com/questions/10202570/…
  • @user14518362 - 这不是 OP 所要求的。 “每年最多票数”。
  • 我试过了,但它给出了一个整体最大值的行。但我需要每一年的最大值行。

标签: python pandas dataframe data-science


【解决方案1】:

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

【讨论】:

  • 谢谢,阿图罗。考虑一个不同的数据集,我如何才能获得每年前 10 名的政党(就获得最大票数而言)?
  • 您可以使用第二种方法并尝试head(10)而不是first()。查看this post
  • 虽然使用 head(10) 打印每年排名前 10 的政党,但为什么在顶部打印最近的年份。我想要年长的那一年。那怎么办?
  • 按年份对新数据进行排序:df.sort_values(Election Yr., ascending=True)。确保reset_index()head(10) 之后。即:df.groupby(....).head(10).reset_index() 然后再排序。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    【讨论】:

    • 谢谢。考虑一个不同的数据集,我如何才能获得每年前 10 名的政党(就获得最大票数而言)?
    • 不要发布图片,也要解释你在做什么
    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多