I have this DataFrame:
data = {'year': [2019,2019,2019,2019,2019,2019,2019,2019,2020,2020,2020,2020,2020,2020],
'month': [1,2,3,4,5,6,7,8,5,6,7,8,9,10],
'val1': [0,0,0,0,1,0,0,0,0,0,1,0,0,0],
'val2': [0,0,1,0,1,0,0,0,1,0,1,0,0,0],
'val3': [0,0,0,0,1,1,0,0,0,0,1,1,0,0]}
df = pd.DataFrame(data)
Printed data:
+------+-------+------+------+------+
| year | month | val1 | val2 | val3 |
+------+-------+------+------+------+
| 2019 | 1 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2019 | 2 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2019 | 3 | 0 | 1 | 0 |
+------+-------+------+------+------+
| 2019 | 4 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2019 | 5 | 1 | 1 | 1 |
+------+-------+------+------+------+
| 2019 | 6 | 0 | 0 | 1 |
+------+-------+------+------+------+
| 2019 | 7 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2019 | 8 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2020 | 5 | 0 | 1 | 0 |
+------+-------+------+------+------+
| 2020 | 6 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2020 | 7 | 1 | 1 | 1 |
+------+-------+------+------+------+
| 2020 | 8 | 0 | 0 | 1 |
+------+-------+------+------+------+
| 2020 | 9 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2020 | 10 | 0 | 0 | 0 |
+------+-------+------+------+------+
Expected Output:
+------+-------+------+------+------+
| year | month | val1 | val2 | val3 |
+------+-------+------+------+------+
| 2019 | 3 | 0 | 1 | 0 |
+------+-------+------+------+------+
| 2019 | 4 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2019 | 5 | 1 | 1 | 1 |
+------+-------+------+------+------+
| 2019 | 6 | 0 | 0 | 1 |
+------+-------+------+------+------+
| 2020 | 5 | 0 | 1 | 0 |
+------+-------+------+------+------+
| 2020 | 6 | 0 | 0 | 0 |
+------+-------+------+------+------+
| 2020 | 7 | 1 | 1 | 1 |
+------+-------+------+------+------+
| 2020 | 8 | 0 | 0 | 1 |
+------+-------+------+------+------+
I need to apply a groupby on the column year and month. But I am only interested in non-zero values in val1, val2 and val3 at the beginning and at the end. Zero values in the middle of the year should not be removed.
Is it possible to check the start of the groups and drop row by row until a valX column has a non-zero value. The same approach reversed from the end of the group.