Home > Software engineering >  Reversing row values in a panda
Reversing row values in a panda

Time:05-14

i'm having a mind wipe, i cannot for the life of me figure out a simple way of reversing this input to the output, any help would be appreciated.

input:

level1 level2 level3 level4
4 2 1 NaN
2 1 NaN NaN

output:

level1 level2 level3 level4
1 2 4 NaN
1 2 NaN NaN

Thanks

CodePudding user response:

Here is one way, using reindexing:

(df
 .apply(lambda s: s.dropna()[::-1].reset_index(drop=True), axis=1)
 .reindex(columns=range(df.shape[1]))
 .set_axis(df.columns, axis=1)
)

output:

   level1  level2  level3  level4
0     1.0     2.0     4.0     NaN
1     1.0     2.0     NaN     NaN

CodePudding user response:

This should give you the results for which you are looking

df.rank(axis = 1, ascending = False)

You will need to work with the results though if you have to remove the float value since there are NaN in your data, but that should be easier to do

  • Related