Pandas rank by column value [duplicate]

本秂侑毒 提交于 2019-11-27 11:47:12

问题


This question already has an answer here:

  • pandas group by year, rank by sales column, in a dataframe with duplicate data 1 answer

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

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_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

回答1:


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

You could groupby on Auction_ID and take rank() on Bid_Price with 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


来源:https://stackoverflow.com/questions/30425796/pandas-rank-by-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!