【问题标题】:Python rank: give negative rank to negative numbersPython排名:给负数负排名
【发布时间】:2022-06-23 02:27:40
【问题描述】:

我有一组基本数据,例如:

ID Value
A  0.1
B  0.2
C  -0.1
D  -0.01
E  0.15

如果我们使用 data.rank() 我们会得到结果:

ID Value
A  3
B  5
C  1
D  2
E  4

但我希望负值导致负排名,例如:

ID Value
A  1
B  3
C  -2
D  -1
E  2

基本上,排名给负值一个负排名,而正值获得一个正排名,但我们得到的不是 1 到 5,而是 1 到 3 和 -1 到 -2。 非常感谢任何帮助。

【问题讨论】:

  • 您的排名值不正确。您如何将正数 [0.1, 0.2, 0.15] 排名为 [2, 3, 1]?
  • 正面排名似乎不正确。你能编辑这个吗?或者确认确实正确
  • 感谢大家的评论,已经编辑好了

标签: python pandas rank


【解决方案1】:

另一种类似于 concat 答案的方法,但不那么紧凑:

import pandas as pd

A = ['A', 'B', 'C', 'D']
B = [-1, 1, 3, -2]

df = pd.DataFrame({'ID': A, 'value': B})

pos = df.where(df['value'] >= 0)['value'].rank()
neg = df.where(df['value'] < 0)['value'].rank()
pos.update(-neg)

df['rank'] = pos
print(df)

输出:

  ID  value  rank
0  A     -1  -2.0
1  B      1   1.0
2  C      3   2.0
3  D     -2  -1.0

【讨论】:

    【解决方案2】:

    分别排列你的正值和负值,然后concat它们:

    >>> pd.concat([df[df["Value"].gt(0)].rank(),df[df["Value"].lt(0)].mul(-1).rank().mul(-1)]).sort_index()
    
        ID  Value
    0  1.0    1.0
    1  2.0    3.0
    2 -1.5   -2.0
    3 -1.5   -1.0
    4  3.0    2.0
    

    【讨论】:

    • 谢谢,这适用于所描述的具体示例,但不能作为一般解决方案
    • 怎么样?除了列名之外,它没有引用任何特定于您的解决方案的内容。
    • 不知道为什么,但是在另一个数据集上运行时会给出错误的值
    【解决方案3】:

    跳出框框思考并整理您的价值观。

    # create your dummy data
    data = pd.DataFrame({'ID':list('ABCDE'), 'Value':[0.1,0.2,-0.1,-0.01,0.15]})
    
    # sort the data so that we can use of the cumsum (and vectorize the operation)
    data = data.sort_values('Value')
    
    # Cumulartive sum of the booleans for the  positive values
    # Minus the the inverse sum of the booleans of the negative values
    data['RANK'] = (data['Value']>=0).cumsum() - (data['Value']<0)[::-1].cumsum() 
    
    # Sort the values back to the original state ...    
    data.sort_values('ID')
    
    
         ID     Value   RANK
    0     A      0.10    1
    1     B      0.20    3
    2     C     -0.10   -2
    3     D     -0.01   -1
    4     E      0.15    2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多