user9394674
user9394674

Reputation:

Delete row beneath specific value pandas

This question is similar to attached except I don't have any np.nan values. How to delete row based on row above? Python Pandas

Essentially I'm just trying to delete the row after a specific value. For the df below I want to delete the row after 'Foo'

import pandas as pd
import numpy as np

d = ({
    'A' : ['X','Y','','X','Y'],           
    'B' : ['Foo',np.nan,'','Foo',np.nan],
    'C' : ['X','Y','','X','Y'],
    })

Can you just shift the following +1?

dl = df.loc[df['B'] != 'Foo']

My intended output is:

   A    B  C
0  X  Foo  X
1           
2  X  Foo  X

Upvotes: 1

Views: 74

Answers (1)

jezrael
jezrael

Reputation: 863116

You need change condition for equal, shift and filter by inverted boolean mask:

dl = df[~(df['B'] == 'Foo').shift().fillna(False)]
print (dl)
   A    B  C
0  X  Foo  X
2           
3  X  Foo  X

Upvotes: 1

Related Questions