Skip to content
Advertisement

Reshaping long format dataframe to wide format according to the number of elements in columns [closed]

I have the following pandas dataframe X in long format:

JavaScript

And I would like to change to the following wide format according the number of alternatives in the group:

JavaScript

i.e. I want to create 4 columns (indexed by 1,2,3,4, the names as in the alt.var column) (the maximum number of alternatives in a group) and column i get assigned 5-i if element i exists in group i and NA or null value if element i does not exists in group i.

I have tried to do a little digging in stackoverflow but it doesn’t seem to match any result.

Advertisement

Answer

You can create a val column with 5 – value in alt.var then pivot

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement