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

Rolling difference dependent on another categorical column changing?

I have a df with the following structure where A is a categorical variable, t is the number of seconds and X is the desired output:

A t X
1 0.0 0
1 3.2 3.2
1 3.9 3.9
1 18.0 18
1 27.4 27.4
3 47.4 0
3 50.2 2.9
3 57.2 9.8
3 64.8 17.4
3 76.4 29.1
2 80.5 0
1 85.3 0
1 87.4 2.1

I would like X to be the number of seconds since column A has changed value.

I can do this in a big for loop but it it is too slow / computationally expensive.

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

I was trying to get the number of rows since the change by doing the following but not quite right and not sure how to index for the change from there regardless:

g = df[A].transform(lambda x: x.diff().ne(0).cumsum())
df[X] = df[A].cumcount() + 1

>Solution :

Use groupby.transform('first') to get the first value per group and subtract this from t:

# group consecutive values
group = df['A'].ne(df['A'].shift()).cumsum()

df['X'] = df['t'].sub(df.groupby(group)['t'].transform('first'))

Output:

    A     t     X
0   1   0.0   0.0
1   1   3.2   3.2
2   1   3.9   3.9
3   1  18.0  18.0
4   1  27.4  27.4
5   3  47.4   0.0
6   3  50.2   2.8
7   3  57.2   9.8
8   3  64.8  17.4
9   3  76.4  29.0
10  2  80.5   0.0
11  1  85.3   0.0
12  1  87.4   2.1
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