Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare current row value to all 6 previous row values

I want to compare a current row value with all the previous 6 row values and return True if it is greater than all 6 of them.

I tried:

df.close > df.close.shift(-6)

However it does not return what I need as it only compares the current row value with values 6 rows back.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is a sample dataframe with close values if you would like to try.
In this example df, the value at index 1495 should return true as 0.604 is greater than all 6 previous values. Thankyou in advance!

close
1479    0.356
1480    0.371
1481    0.359
1482    0.386
1483    0.388
1484    0.362
1485    0.362
1486    0.310
1487    0.314
1488    0.349
1489    0.351
1490    0.387
1491    0.423
1492    0.416
1493    0.450
1494    0.561
1495    0.604
1496    0.571
1497    0.539
1498    0.537

>Solution :

You can try Series.rolling. Here use window 7 is to not include current row in previous 6 rows

df['res'] = (df['close'].rolling(window=7, min_periods=1)
             .apply(lambda w: w.iloc[:-1].lt(w.iloc[-1]).all()))
print(df)

      close  res
1479  0.356  1.0
1480  0.371  1.0
1481  0.359  0.0
1482  0.386  1.0
1483  0.388  1.0
1484  0.362  0.0
1485  0.362  0.0
1486  0.310  0.0
1487  0.314  0.0
1488  0.349  0.0
1489  0.351  0.0
1490  0.387  1.0
1491  0.423  1.0
1492  0.416  0.0
1493  0.450  1.0
1494  0.561  1.0
1495  0.604  1.0
1496  0.571  0.0
1497  0.539  0.0
1498  0.537  0.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading