2

I want to shift rows in a pandas df when values are equal to a specific value in a Column. For the df below, I'm trying to shift the values in Column B to Column A when values in A == x.

import pandas as pd

df = pd.DataFrame({
    'A' : [1,'x','x','x',5],
    'B' : ['x',2,3,4,'x'],
        })

This is my attempt:

df = df.loc[df.A.shift(-1) == df.A.shift(1), 'x'] = df.A.shift(1)

Intended Output:

   A  B
0  1  x
1  2
2  3
3  4
4  5  x

2 Answers 2

4

You can use:

m = df.A.eq('x')
df[m]=df[m].shift(-1,axis=1)
print(df)

   A    B
0  1    x
1  2  NaN
2  3  NaN
3  4  NaN
4  5    x
Sign up to request clarification or add additional context in comments.

Comments

2

You can use:

df[df.A=='x'] = df.shift(-1,axis=1)

print(df)

   A    B
0  1    x
1  2  NaN
2  3  NaN
3  4  NaN
4  5    x

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.