python - Incrementing contiguous positive groups in array/Series -
suppose have pandas series of boolean values so.
vals = pd.series([0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1]).astype(bool) >>> vals 0 false 1 false 2 false 3 true 4 true 5 true 6 true 7 false 8 false 9 true 10 true 11 false 12 true 13 true 14 true dtype: bool
i want turn boolean series series each group of 1's enumerated,
0 0 1 0 2 0 3 1 4 1 5 1 6 1 7 0 8 0 9 2 10 2 11 0 12 3 13 3 14 3
how can efficiently?
i have been able manually, looping on series on python level , incrementing, slow. i'm looking vectorized solution - saw this answer unutbu concerning splitting on increasing groups in numpy, , trying work cumsum
of sort have been unsuccessful far.
you can try this:
vals.astype(int).diff().fillna(vals.iloc[0]).eq(1).cumsum().where(vals, 0) #0 0 #1 0 #2 0 #3 1 #4 1 #5 1 #6 1 #7 0 #8 0 #9 2 #10 2 #11 0 #12 3 #13 3 #14 3 #dtype: int64
Comments
Post a Comment