如何在多列中使用pandas对python中的行进行排名

问题描述 投票:0回答:1

假设我有以下pandas数据帧,我需要在新列排名行(我的意思是,如果我想排名4行,我将创建4个新行)

在下面的数据框中,我有三个数字列,我需要比较和排名每一行,有三行所以我需要三个新列来比较每个colmuns中的值与行

Revenue-SaleCount-salesprices-ranka-rankb-rankc

300------10-----------8000--------2--------1-----3

100----9000-----------1000--------1--------3-----2

我怎么能用简单的代码和使用for循环提前做到这一点

import pandas as pd

df = pd.DataFrame({'Revenue':[300,9000,1000,750,500,2000,0,600,50,500],
    'Date':['2016-12-02' for i in range(10)],
    'SaleCount':[10,100,30,35,20,100,0,30,2,20],
    'salesprices':[8000,1000,500,700,2500,3800,16,7400,3200,21]})


print(df)
python pandas python-2.7 dataframe ranking
1个回答
2
投票

我们可以用string.ascii_lowercase编写一个循环,并在rank上用axis=1创建每一列

import string

cols = ['Revenue', 'SaleCount', 'salesprices']

for index, col in enumerate(cols):
    df[f'rank{string.ascii_lowercase[index]}'] = df[cols].rank(axis=1)[col]

输出:

print(df)
   Revenue        Date  SaleCount  salesprices  ranka  rankb  rankc
0      300  2016-12-02         10         8000    2.0    1.0    3.0
1     9000  2016-12-02        100         1000    3.0    1.0    2.0
2     1000  2016-12-02         30          500    3.0    1.0    2.0
3      750  2016-12-02         35          700    3.0    1.0    2.0
4      500  2016-12-02         20         2500    2.0    1.0    3.0
5     2000  2016-12-02        100         3800    2.0    1.0    3.0
6        0  2016-12-02          0           16    1.5    1.5    3.0
7      600  2016-12-02         30         7400    2.0    1.0    3.0
8       50  2016-12-02          2         3200    2.0    1.0    3.0
9      500  2016-12-02         20           21    3.0    1.0    2.0

注意我使用的f-string仅支持Python版本> 3.4。否则使用.format字符串格式如下:

import string

cols = ['Revenue', 'SaleCount', 'salesprices']

for index, col in enumerate(cols):
    df['rank{}'.format(string.ascii_lowercase[index])] = df[cols].rank(axis=1)[col] 
© www.soinside.com 2019 - 2024. All rights reserved.