I have the following data frame.
sensor_id | u_code | ts |
---|---|---|
abcd | 5 | 2022-06-17 16:22:41 |
abcd | 1 | 2022-06-17 16:22:42 |
abcd | 5 | 2022-06-17 16:22:43 |
abcd | 6 | 2022-06-17 16:22:44 |
abcd | 1 | 2022-06-17 16:22:45 |
abcd | 1 | 2022-06-17 16:22:46 |
abcd | 1 | 2022-06-17 16:22:47 |
abcd | 8 | 2022-06-17 16:22:48 |
efgh | 4 | 2022-06-17 16:22:49 |
efgh | 4 | 2022-06-17 16:22:50 |
efgh | 2 | 2022-06-17 16:22:51 |
efgh | 5 | 2022-06-17 16:22:52 |
efgh | 5 | 2022-06-17 16:22:53 |
efgh | 5 | 2022-06-17 16:22:54 |
efgh | 5 | 2022-06-17 16:22:55 |
efgh | 3 | 2022-06-17 16:22:56 |
efgh | 3 | 2022-06-17 16:22:57 |
efgh | 3 | 2022-06-17 16:22:58 |
efgh | 5 | 2022-06-17 16:22:59 |
efgh | 3 | 2022-06-17 16:23:00 |
efgh | 3 | 2022-06-17 16:23:01 |
efgh | 3 | 2022-06-17 16:23:02 |
efgh | 6 | 2022-06-17 16:23:03 |
What I need is that, when ever the u_code is 1, 2 or 3; I want to compare it against the u_code other than itself immediately before it and after it. If the u_code before and after are same, I want to ignore them and only show the dataframe where the u_code before and after a sequence of 1, 2 or 3 are different. Also, I want a check if the sensor ID is same when the comparison is done.
Below is my expected output.
sensor_id | u_code | ts |
---|---|---|
abcd | 6 | 2022-06-17 16:22:44 |
abcd | 1 | 2022-06-17 16:22:45 |
abcd | 1 | 2022-06-17 16:22:46 |
abcd | 1 | 2022-06-17 16:22:47 |
abcd | 8 | 2022-06-17 16:22:48 |
efgh | 4 | 2022-06-17 16:22:50 |
efgh | 2 | 2022-06-17 16:22:51 |
efgh | 5 | 2022-06-17 16:22:52 |
efgh | 5 | 2022-06-17 16:22:59 |
efgh | 3 | 2022-06-17 16:23:00 |
efgh | 3 | 2022-06-17 16:23:01 |
efgh | 3 | 2022-06-17 16:23:02 |
efgh | 6 | 2022-06-17 16:23:03 |
My desired output is marked in brown in the picture below.
To explain with examples
- in the first green marked zone, the sensor_id is abcd and u_code before 1 is 5 and after 1 is also 5. So we can filter this out as the u_code has not changed after the sequence of 1.
- in the next area marked in brown, we have sensor_id abcd and a u_code 1 preceded by u_code 6. The u_code after 1 is again 1 followed by another 1. We keep looking for a u_code other than 1 with same sensor_id and finally reach 8. As 8 is different to the u_code 6 which was prior to the sequence of 1's , we want to keep this part of the data frame.
Similar checks are needed for u_codes 2 and 3 also.
2022-06-17 16:22:46
or2022-06-17 16:23:01
? There is the same value before and after. Also do you need to consider per sensor_id?