pandas 按列值排列 [英] Pandas rank by column value

查看:271
本文介绍了 pandas 按列值排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有拍卖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


解决方案

这是以熊猫方式做的一种方式



您可以在 Auction_ID 并将 rank() Bid_Price 升序= False

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

在[69]中:df
出[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


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

解决方案

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

这篇关于 pandas 按列值排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆