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.
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