Keep rows where string is followed by separate specific string – pandas

Using below, I'm hoping to drop any rows that are equal to X that aren't directly followed by BKE or DKE in the previous row. Furthermore, Time should be identical between BKE, DKE and X, otherwise X should also be dropped.

df = pd.DataFrame({      
    'Time' : [1,1,1,2,2,2,3,3,3],
    'Item' : ['A','BKE','X','Y','X','DKE','X','Y','X'],          
   })

df = df[~(df['Item'].isin(['BKE','DKE'])) & (df['Item'] == 'X').shift(1)]

intended output:

   Time Item
0     1    A
1     1  BKE
2     1    X
3     2    Y
4     2  DKE
5     3    Y


Read more here: https://stackoverflow.com/questions/66995974/keep-rows-where-string-is-followed-by-separate-specific-string-pandas

Content Attribution

This content was originally published by Chopin 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: