Search code examples
pythonpandasrank

Python rank: give negative rank to negative numbers


I have a basic set of data like:

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

If we use data.rank() we get the result:

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

But i want to have so that the negative values result in an negative rank instead such as:

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

Basically rank give the negative values an negative rank while the postive values get a positive rank but instead of 1 to 5 we get 1 to 3 and -1 to -2. Any help is greatly apreciated.


Solution

  • Another method similar to the concat answer, but not as compact:

    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(ascending=False)
    pos.update(-neg)
    
    df['rank'] = pos
    print(df)
    

    Output:

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

    Edit: I noticed that the negative rank did not follow the order you specified in your post, so I added "ascending=False" in rank() to address that.