'Reversing row values in a panda
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
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mozway |
Solution 2 | ArchAngelPwn |