Group consecutive rises and falls using Pandas Series

29 Views Asked by At

I want to group consecutive growth and falls in pandas series. I have tried this, but it seems not working:

consec_rises = self.df_dataset.diff().cumsum()
group_consec = consec_rises.groupby(consec_rises)

My dataset:

date
2022-01-07     25.847718
2022-01-08     29.310294
2022-01-09     31.791339
2022-01-10     33.382136
2022-01-11     31.791339
2022-01-12     29.310294
2022-01-13     25.847718
2022-01-14     21.523483
2022-01-15     16.691068
2022-01-16     11.858653
2022-01-17      7.534418

I want to get result as following:

Group #1 (consecutive growth)
2022-01-07     25.847718
2022-01-08     29.310294
2022-01-09     31.791339
2022-01-10     33.382136
    
Group #2 (consecutive fall)
2022-01-12     29.310294
2022-01-13     25.847718
2022-01-14     21.523483
2022-01-15     16.691068
2022-01-16     11.858653
2022-01-17      7.534418
1

There are 1 best solutions below

0
Andrej Kesely On

If I understand you correctly:

mask = df["date"].diff().bfill() >= 0

for _, g in df.groupby((mask != mask.shift(1)).cumsum()):
    print(g)
    print("-" * 80)

Prints:

                 date
2022-01-07  25.847718
2022-01-08  29.310294
2022-01-09  31.791339
2022-01-10  33.382136
--------------------------------------------------------------------------------
                 date
2022-01-11  31.791339
2022-01-12  29.310294
2022-01-13  25.847718
2022-01-14  21.523483
2022-01-15  16.691068
2022-01-16  11.858653
2022-01-17   7.534418
--------------------------------------------------------------------------------