Conditional length of a binary data series in Pandas
<p>Having a DataFrame with the following column:</p>

<pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1]
</code></pre>

<p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p>

<pre><code>   A  B
0  1  1
1  1  1
2  1  0
3  0  0
4  1  1
5  1  1
6  1  0
7  1  0
8  0  0
9  1  1
</code></pre>

<p>One fully-vectorized solution is to use the <code>shift</code>-<code>groupby</code>-<code>cumsum</code>-<code>cumcount</code> combination<sup>1</sup> to indicate where consecutive runs are shorter than 2 (or whatever limiting value you like). Then, <code>&amp;</code> this new boolean Series with the original column:</p>

<pre><code>df['B'] = ((df.groupby((df.A != df.A.shift()).cumsum()).cumcount() &lt;= 1) &amp; df.A)\
          .astype(int) # cast the boolean Series back to integers
</code></pre>

<p>This produces the new column in the DataFrame:</p>

<pre><code>   A  B
0  1  1
1  1  1
2  1  0
3  0  0
4  1  1
5  1  1
6  1  0
7  1  0
8  0  0
9  1  1
</code></pre>

<hr>

<p><sup>1</sup> See the <a href="http://pandas.pydata.org/pandas-docs/stable/cookbook.html#grouping" rel="nofollow">pandas cookbook</a>; the section on grouping, "Grouping like Pythonâs itertools.groupby"</p>

python pandas vectorization