使用Pandas按列值排名

40

我有一个数据框,里面有拍卖ID和竞标价格。该数据框按照拍卖ID(升序)和竞标价格(降序)排序:

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

我想添加一列名为“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

为什么出价为9和1的竞标价格都具有排名1?以及为什么拍卖ID 124和125,两者均为出价1,具有不同的排名? - jbuddy_13
1个回答

62

以下是使用Pandas方法完成的一种方式:

您可以在 Auction_ID 上进行groupby操作,并在 Bid_Price 上使用 rank() 方法,并设置参数ascending=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

1
如果您想仅按Auction_ID==124分组怎么办?类似于R中的dpylr过滤函数。 - Gabriel Fair
df['Auction_Rank'] = df.loc[df['Auction_ID'] == 124, :].groupby('Auction_ID')['Bid_Price'].rank(ascending=False) - moto
如果需要排除一个特定的列,该怎么办? - Yog
3
@Zero 这个答案对我来说不起作用。代码如下:df = pd.DataFrame({'Auction_ID':[1,2,3,4], 'Bid_Price':[7, 10, 5, 3]}); df['Auction_Rank'] = df.groupby('Auction_ID')['Bid_Price'].rank(ascending=False); 在Auction_Rank列中,df返回[1,1,1,1]。 - shahar_m
如果所有列都是字符串,会怎样? - ashish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接