简体   繁体   中英

Delete a row from a Pandas df if the previous row is equal to some value

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
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

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')]

   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM