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

How can I create groups based on ascending streak of a column?

This is my DataFrame:

import pandas as pd
df = pd.DataFrame(
    {
        'a': [10, 14, 20, 10, 12, 5, 3]
    }
)

And this is the expected output. I want to create four groups:

    a
0  10
1  14
2  20

    a
3  10
4  12

    a
5   5

    a 
6   3 

From top to bottom, as far as a is increasing/equal groups do not change. That is why first three rows are in one group. However, in row 3 a has decreased (i.e. 20 > 10). So this is where the second group starts. And the same logic applies for the rest of groups.

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

This is one my attempts. But I don’t know how to continue:

import numpy as np
df['dir'] = np.sign(df.a.shift(-1) - df.a)

>Solution :

Code

maybe there are 4 groups

dfs = [d for _, d in df.groupby(df['a'].diff().lt(0).cumsum())]

dfs

[    a
 0  10
 1  14
 2  20,
     a
 3  10
 4  12,
    a
 5  5,
    a
 6  3]
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