Home > Back-end >  How to retrieve pandas dataframe rows surrounding rows with a True boolean?
How to retrieve pandas dataframe rows surrounding rows with a True boolean?

Time:05-02

Suppose I have a df of the following format:

enter image description here

Assumed line 198 would be True for rot_mismatch, what would be the best way to retrieve the True line (easy) and the line above and below (unsolved)?

I have multiple lines with a True boolean and would like to automatically create a dataframe for closer investigation, always including the True line and its surrounding lines.

Thanks!

CodePudding user response:

Is it what you want ?

df_true=df.loc[df['rot_mismatch']=='True',:]
df_false=df.loc[df['rot_mismatch']=='False',:]

CodePudding user response:

Try with shift:

>>> df[df["rot_mismatch"]|df["rot_mismatch"].shift()|df["rot_mismatch"].shift(-1)]
        dep_ap_sched     arr_ap_sched  rot_mismatch
120      East Carmen  South Nathaniel         False
198  South Nathaniel      East Carmen          True
289      East Carmen       Joneshaven         False
  • Related