如何在python中修改pandas中的排名

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

我有一个pandas数据帧如下。

item   x1 x2 x3 x4 x5 ratings
item1   x  x  x  x  x  46
item1   x  x  x  x  x  32
item1   x  x  x  x  x  16
item1   x  x  x  x  x  6
item1   x  x  x  x  x  36
item1   x  x  x  x  x  36
item1   x  x  x  x  x  12
item1   x  x  x  x  x  13
item1   x  x  x  x  x  41
item1   x  x  x  x  x  42
item1   x  x  x  x  x  43
item1   x  x  x  x  x  3
item1   x  x  x  x  x  76
item1   x  x  x  x  x  36
item1   x  x  x  x  x  26
item1   x  x  x  x  x  12
item1   x  x  x  x  x  11
item1   x  x  x  x  x  88
item1   x  x  x  x  x  87
item1   x  x  x  x  x  78
item1   x  x  x  x  x  43
item1   x  x  x  x  x  42

现在,我想用rankingsratings添加另一列。

我做得很好用;

df = df.assign(rankings=df.rank(ascending=False))

我想再次重新排列排名列,并在数据框中添加不同的列,如下所示。

  • 排名从1-10 - >获得排名1
  • 排名从11-20 - >获得排名2
  • 排名从21-30 - >获得排名3
  • 等等

有没有办法在python中的pandas中做到这一点?

如果需要,我很乐意提供更多细节。

python pandas
1个回答
3
投票

使用10的整数除法并添加1,最后转换为整数:

df = df.assign(rankings=df['ratings'].rank(ascending=False))
df['new'] = (df['rankings'] // 10 + 1).astype(int)
print (df)
     item x1 x2 x3 x4 x5  ratings  rankings  new
0   item1  x  x  x  x  x       46       5.0    1
1   item1  x  x  x  x  x       32      14.0    2
2   item1  x  x  x  x  x       16      16.0    2
3   item1  x  x  x  x  x        6      21.0    3
4   item1  x  x  x  x  x       36      12.0    2
5   item1  x  x  x  x  x       36      12.0    2
6   item1  x  x  x  x  x       12      18.5    2
7   item1  x  x  x  x  x       13      17.0    2
8   item1  x  x  x  x  x       41      10.0    2
9   item1  x  x  x  x  x       42       8.5    1
10  item1  x  x  x  x  x       43       6.5    1
11  item1  x  x  x  x  x        3      22.0    3
12  item1  x  x  x  x  x       76       4.0    1
13  item1  x  x  x  x  x       36      12.0    2
14  item1  x  x  x  x  x       26      15.0    2
15  item1  x  x  x  x  x       12      18.5    2
16  item1  x  x  x  x  x       11      20.0    3
17  item1  x  x  x  x  x       88       1.0    1
18  item1  x  x  x  x  x       87       2.0    1
19  item1  x  x  x  x  x       78       3.0    1
20  item1  x  x  x  x  x       43       6.5    1
21  item1  x  x  x  x  x       42       8.5    1
© www.soinside.com 2019 - 2024. All rights reserved.