+1 vote
in Programming Languages by (51.8k points)
edited by
I want to compute the rank of data items by multiple columns of a dataframe. Is there any option with the rank() function use multiple columns?

1 Answer

+1 vote
by (281k points)
selected by
 
Best answer

To use multiple columns of a dataframe to apply the rank() function, you can provide multiple columns as a list.

The function will return the rank of the data items in those columns. In the following example, I have used the 'first' method in the rank function. It will assign rank in the order they appear in the column.

>>> import pandas as pd

>>> df=pd.DataFrame({'A':[4,6,3,1,8], 'B':[43,12,54,34,67], 'C':[32,45,12,68,43]})

>>> df

   A   B   C

0  4  43  32

1  6  12  45

2  3  54  12

3  1  34  68

4  8  67  43

>>> df[['A','B']].rank(method='first')

     A    B

0  3.0  3.0

1  4.0  1.0

2  2.0  4.0

3  1.0  2.0

4  5.0  5.0


...