pandas 熊猫按列值排名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30425796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:40:15  来源:igfitidea点击:

Pandas rank by column value

pandasdataframerank

提问by Christopher Jenkins

I have a dataframe that has auction IDs and bid prices. The dataframe is sorted by auction id (ascending) and bid price (descending):

我有一个包含拍卖 ID 和出价的数据框。数据框按拍卖 ID(升序)和出价(降序)排序:

Auction_ID    Bid_Price
123           9
123           7
123           6
123           2
124           3
124           2
124           1
125           1

I'd like to add a column called 'Auction_Rank' that ranks auction id's by bid prices:

我想添加一个名为“Auction_Rank”的列,按出价对拍卖 ID 进行排名:

Auction_ID    Bid_Price    Auction_Rank
123           9            1
123           7            2
123           6            3
123           2            4
124           3            1
124           2            2
124           1            3
125           1            1

回答by Zero

Here's one way to do it in Pandas-way

这是在 Pandas-way 中实现的一种方法

You could groupbyon Auction_IDand take rank()on Bid_Pricewith ascending=False

你可以groupbyAuction_ID,并采取rank()Bid_Priceascending=False

In [68]: df['Auction_Rank'] = df.groupby('Auction_ID')['Bid_Price'].rank(ascending=False)

In [69]: df
Out[69]:
   Auction_ID  Bid_Price  Auction_Rank
0         123          9             1
1         123          7             2
2         123          6             3
3         123          2             4
4         124          3             1
5         124          2             2
6         124          1             3
7         125          1             1