John
John

Reputation: 515

Reverse Values Based on Successive Count

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

Answers (2)

BENY
BENY

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

piRSquared
piRSquared

Reputation: 294338

  • Use diff().ne(0) to find the breaks
  • Use cumsum() to create the groups
  • Use groupby.transform('size') to count the size of groups
  • then flip value with sub(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

Related Questions