Reputation: 515
I have a series containing only 1's and 0's used as a flag. I'm trying to figure out a good way to count the number of successive repeat values, and if it doesn't meet a threshold, I'd like to reverse them. For instance, if I have less than 5 repeated values in succession, reverse them from 0's to 1's or vice versa.
For example:
Flag
1
1
1
1
1
0
0
0
0
1
1
...
Would become:
Flag
1
1
1
1
1
1
1
1
1
1
1
...
Upvotes: 2
Views: 36
Reputation: 323306
Just try another way maybe
s=df.Flag.diff().ne(0).cumsum().value_counts()
np.where(((s>=5).repeat(s).values),df.Flag,1-df.Flag)
Out[1158]: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], dtype=int64)
Upvotes: 1
Reputation: 294338
diff().ne(0)
to find the breakscumsum()
to create the groupsgroupby.transform('size')
to count the size of groupssub(df.Flag).abs()
df.Flag.groupby(
df.Flag.diff().ne(0).cumsum()
).transform('size').lt(5).sub(df.Flag).abs()
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 0
10 0
Name: Flag, dtype: int64
Upvotes: 5