id101112
id101112

Reputation: 1042

How can I filter rows before and after in pandas dataframe

I have this whol dataframe I have these flagged and unflagged rows, i want to filter out the rows before and after the flagged row and also need the flagged row to,

so my data is

index            DateTime       A1   A2   A4        AMS  ID          flCol
16610745    2011-01-03T13:15:00 130 122 368010037   128 003669730   notflagged
16610745    2011-01-03T13:15:00 130 122 368010037   128 003669730   notflagged
16610747    2011-01-03T13:15:59 112 103 368010037   128 003669730   notflagged
16610749    2011-01-03T13:17:00 95  90  368010037   128 003669730   flagged
16610751    2011-01-03T13:18:00 75  67  368010037   128 003669730   notflagged
16610753    2011-01-03T13:18:59 42  33  368010037   128 003669730   notflagged
16610755    2011-01-03T13:20:00 14  7   368010037   128 003669794   notflagged

and i need only like this way, the point before flagged one, after one, and the one which is flagged?

   16610747 2011-01-03T13:15:59 112 103 368010037   128 003669730   notflagged
   16610749 2011-01-03T13:17:00 95  90  368010037   128 003669730   flagged
   16610751 2011-01-03T13:18:00 75  67  368010037   128 003669730   notflagged

and I need the complete row in a pandas dataframe

Upvotes: 0

Views: 703

Answers (1)

Ben.T
Ben.T

Reputation: 29635

you can create a mask with all the condition on the column 'flCol' and shift to look for the row before or after

mask = ( (df['flCol'] == 'flagged')|
         (df['flCol'].shift(1) == 'flagged')|
         (df['flCol'].shift(-1) == 'flagged') )

Then df[mask] should contains the data you want

Upvotes: 2

Related Questions