Home > database >  Python: Get sorting position of the values of every row in a table
Python: Get sorting position of the values of every row in a table

Time:11-08

Based on my Question here ist there a way to transform the Matrix based on a .csv-file

Date Company1 Company2 Company3
01.01.2020 1.01 0.9 1
02.01.2020 0.9 2.2 2
... ... ... ...
24.10.2020 1.02 1.01 1.03

into a .csv-file of form

Date Company1 Company2 Company3
01.01.2020 1 3 2
02.01.2020 3 1 2
... ... ... ...
24.10.2020 2 3 1

Whereby Companyx gets:

  • value 1, iff companyx has the biggest value in the base matrix on given date y
  • value 2, iff companyx has the middle value in the base matrix on given date y
  • value 3, iff companyx has the smallest value in the base matrix on given date y

CodePudding user response:

You can use the built in rank function to solve this problem, passing axis=1 to indicate a row-wise ranking.

df.set_index('Date').rank(axis=1, ascending=False).reset_index()

Output

         Date  Company1  Company2  Company3
0  01.01.2020       1.0       3.0       2.0
1  02.01.2020       3.0       1.0       2.0
2  24.10.2020       2.0       3.0       1.0
  • Related