I have a df
index id action
1 A crawl
2 A walk
3 A run
4 B crawl
5 B run
6 B walk
7 B jump
8 B walk
I want to delete a certain row with text walk
only if the previous row is run
.
Resulting df:
index id action
1 A crawl
2 A walk
3 A run
4 B crawl
5 B run
7 B jump
8 B walk
CodePudding user response:
df = df.drop(df[df['action'].eq('run').shift(1, fill_value=False) & df['action'].eq('walk')].index, axis=0)
Output:
>>> df
index id action
0 1 A crawl
1 2 A walk
2 3 A run
3 4 B crawl
4 5 B run
6 7 B jump
7 8 B walk
CodePudding user response:
This is your dataframe:
import pandas as pd
dataset = pd.DataFrame(
{'index':list(range(1,9)),'id': ['A', 'A', 'A', 'B', 'B', 'B','B','B'],
'action': ['crawl','walk','run','crawl','run','walk','jump','walk']})
Then you can create a temp column with shifting action by one and write this condition:
dataset[(dataset.action!='walk') | (dataset['action'].shift(1)!='run')]