user3368835
user3368835

Reputation: 367

Reverse Row Values in Pandas DataFrame

I'm working on a pandas data frame where I want to find the farthest out non-null value in each row and then reverse the order of those values and output a data frame with the row values reversed without leaving null values in the first column. Essentially reversing column order and shifting non-null values to the left.

IN:

   1  2  3  4  5
1  a  b  c  d  e
2  a  b  c
3  a  b  c  d
4  a  b     c

OUT:

   1  2  3  4  5
1  e  d  c  b  a
2  c  b  a
3  d  c  b  a
4  c     b  a

Upvotes: 3

Views: 589

Answers (1)

Code Different
Code Different

Reputation: 93161

For each row, create a new Series with the same indexes but with the values reversed:

def reverse(s):
    # Strip the NaN on both ends, but not in the middle
    idx1 = s.first_valid_index()
    idx2 = s.last_valid_index()
    idx = s.loc[idx1:idx2].index

    return pd.Series(s.loc[idx[::-1]].values, index=idx)

df.apply(reverse, axis=1)

Result:

    1    2  3    4    5
1   e    d  c    b    a
2   c    b  a  NaN  NaN
3   d    c  b    a  NaN
4   c  NaN  b    a  NaN

Upvotes: 3

Related Questions