Using pandas dataframe to output rank in sorted order

Viewed 229

This is my dataframe.

Date        CA  KY  ID  CO
2003-01-31  5   -6   7   1
2003-02-28  6    2  -2  -5
2003-03-31  3   -8   4  -1

I am wondering how I can get the below DataFrame as output. I know it's not argsort() since that gives me the indices in order.

Date        CA  KY  ID  CO
2003-01-31  2    0   3   1
2003-02-28  3    2   1   0
2003-03-31  2    0   3   1

If I wanted to rank them in descending order as well, how would I do that? I guess the number of columns minus the numeric columns would work.

1 Answers
df.rank(axis=1, method='first')

returns:

             CA KY  ID  CO
Date                
2003-01-31  3.0 1.0 4.0 2.0
2003-02-28  4.0 3.0 2.0 1.0
2003-03-31  3.0 1.0 4.0 2.0

If you want exactly the same you can do :

df.rank(axis=1, method='first') - 1

            CA  KY  ID  CO
Date                
2003-01-31  2.0 0.0 3.0 1.0
2003-02-28  3.0 2.0 1.0 0.0
2003-03-31  2.0 0.0 3.0 1.0

For descending order:

df.rank(axis=1, method='first', ascending=False)
Related