jonboy
jonboy

Reputation: 368

Shift rows in a Column when equal to specific value

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

Upvotes: 2

Views: 378

Answers (2)

anky
anky

Reputation: 75080

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

Upvotes: 4

heena bawa
heena bawa

Reputation: 828

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

Upvotes: 2

Related Questions