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

Grouping the same value based on a column increment using Python pandas

what I am trying to do is group values ​​of 0 in a certain period of time using a python dataframe for example I have:

| Time (seconds) | Value |
|       1        |   0   |
|       2        |   0   |
|       3        |   0   |
|       4        |   1   |
|       5        |   0   |
|       6        |   1   |
|       7        |   1   |
|       8        |   0   |
|       9        |   0   |
|       10       |   0   |
|       11       |   1   |
|       12       |   0   |
|       13       |   0   |

And the output what I’m expecting is:

| Time (seconds) | Value | Group |
|       1        |   0   |   1   |
|       2        |   0   |   1   |
|       3        |   0   |   1   |
|       4        |   1   |       |
|       5        |   0   |   2   |
|       6        |   1   |       |
|       7        |   1   |       |
|       8        |   0   |   3   |
|       9        |   0   |   3   |
|       10       |   0   |   3   |
|       11       |   1   |       |
|       12       |   0   |   4   |
|       13       |   0   |   4   |

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

>Solution :

You can check when the value change using shift, cumsum, and mask:

s = df['value'].eq(0)
df['group'] = (s&s.ne(s.shift())).cumsum().where(s, 0)

Output:

    time  value  group
0      1      0      1
1      2      0      1
2      3      0      1
3      4      1      0
4      5      0      2
5      6      1      0
6      7      1      0
7      8      0      3
8      9      0      3
9     10      0      3
10    11      1      0
11    12      0      4
12    13      0      4
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