Search code examples
pythonpandassortingranking

How do I rank values of Pandas row into separate dataframe?


My Dataframe having df.shape (500,15) has different values between (-1,1).

df.head()

0            -0.2966                 -0.1140  ...   0.4699      0.1250
1            -0.3051                 -0.1157  ...   0.6686      0.3290
2            -0.2014                 -0.1427  ...   0.4758      0.4919
3            -0.2703                 -0.0928  ...   0.6004      0.2436
4            -0.3399                 -0.0964  ...   0.3777      0.4808

I want to create a seperate dataframe which gives rank of the column in that specific row. For example, df_rank (seperate df) first row would be ranks with largest number in the row being ranked 1 and lowest being ranked 15, without changing position/sorting. Same for second row and so on.

df_rank

0    11    8....    3    7
1    12    8....    1    3
2    13    7....    2    4
3    11    6....    3    6
4    12    6....    2    7

So on for all 500 rows...


Solution

  • Use DataFrame.rank:

    df = df.rank(axis=1, ascending=False, method='dense').astype(int)
    print (df)
       0  1  2  3
    0  4  3  1  2
    1  4  3  1  2
    2  4  3  2  1
    3  4  3  1  2
    4  4  3  2  1