简体   繁体   中英

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

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

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