Try to search your question here, if you can't find : Ask Any Question Now ?

Shift rows in a Column when equal to specific value

HomeCategory: stackoverflowShift rows in a Column when equal to specific value
pushpa asked 2 weeks ago

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
1 Answers
Best Answer
Fernando answered 2 weeks ago
Your Answer

1 + 9 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com