I'm hoping to drop rows if the string after a specific value is not equal to a list of value. Specifically, if the subsequent row after either 'Up' or 'Left' is not followed by 'Right' or 'Down' then I'm aiming to drop those rows.
import pandas as pd
df = pd.DataFrame({
'Label' : ['A','B','A','B','B','B','A','B','B','A','A','A'],
'Item' : ['X','Left','X','Left','Down','Right','Up','Y','Right','Y','Right','Up'],
})
df1 = df[~(df['Item'].isin(['Up','Left']).shift(1)) & (df['Item'].isin(['Right','Down']))]
Label Item
0 A X
1 B Left
2 A X # Drop. Not Right/Down
3 B Left
4 B Down # Keep. Right/Down
5 B Right
6 A Up
7 B Y # Drop. Not Right/Down
8 B Right
9 A Y
10 A Right
11 A Up
intended output:
Label Item
0 A X
1 B Left
3 B Left
4 B Down
5 B Right
6 A Up
8 B Right
9 A Y
10 A Right
11 A Up