Home > database >  How to change the way ranked survey data is stored in a pandas dataframe?
How to change the way ranked survey data is stored in a pandas dataframe?

Time:07-30

I have a set of questions for which I have ranked data, and it looks like

Y     4     3     2     1 
___________________________
1     A     B     D     C

0     C     D     B     A

0     B     C     D     A

I would like to convert it into the following form to run analyses.

Y     A     B     C     D
___________________________
1     4     3     1     2

0     1     2     4     3

0     1     4     3     2

Is there a way to do this without using for loops?

CodePudding user response:

You can try sort the values based on row then convert its column header to list

out = (df.apply(lambda row: row.sort_values().index.to_list(), axis=1, result_type='expand')
       .set_axis(['A', 'B', 'C', 'D'], axis=1))
print(out)

   A  B  C  D
1  4  3  1  2
0  1  2  4  3
0  1  4  3  2
  • Related