3

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.