Home > Software design >  Dataframe if a condition is met on a dataframe column then get this row and the next 3 rows in a dat
Dataframe if a condition is met on a dataframe column then get this row and the next 3 rows in a dat

Time:02-01

I want to write a code so that if a condition is met on a dataframe column then I can get this row and the next 3 rows in a dataframe?

Each time my funding rate is greater than 0.0363 I want that row and the next 3 rows of the matched row.

enter image description here

CodePudding user response:

You can use reduce from the built-in module functools to do it dynamically:

import functools

N = 3
cond = df['Funding Rate'].str.strip('%').astype(float).gt(0.0363)
df[functools.reduce(lambda x, y: x | y, [cond.shift(i) for i in range(N   1)])]
  •  Tags:  
  • Related