Shift several parts inside one dataframe in pandas with condition

I have a dataframe as below. For simpicity, it has columns A, B, Correctly Shifted(what I want to get) and Incorrectly Shifted (what I have now). I want to shift values in column 'A' based on condition in column 'B'. If I will use pd.DataFrame.shift(1) then it shifts the whole column by 1. But I want to shift using a kind of moving window i.e. shift several parts inside one dataframe. For example, I want to shift all rows in column 'A' by 1 based on values in column 'B' i.e. shift all rows with condition 'aaa', then shift all rows with condition 'bbb' and all rows with condition 'ccc' etc. In column 'Correctly Shifted' is what I want and in column 'Incorrectly Shifted' is what I get if just use shift method in pandas. What is the best approach to solve it?

A B Correctly Shifted Incorrectly Shifted
100 aaa nan nan
110 aaa 100 100
120 aaa 110 110
100 bbb nan 120
110 bbb 100 100
120 bbb 110 110
100 ccc nan 120
110 ccc 100 100
120 ccc 110 110


Read more here: https://stackoverflow.com/questions/68466307/shift-several-parts-inside-one-dataframe-in-pandas-with-condition

Content Attribution

This content was originally published by Roman Lents at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: