fast way to put ones beetween ones in each row of a numpy 2d array
<p>I have a 2d array (Q) consisting of just zeros and ones. I wish to fill with 1 each position between 1's of each line Q. Here's an example:</p>

<p><strong>Original matrix:</strong></p>

<pre><code>[0 0 0 1 0 1]
[1 0 0 0 0 0]
[0 0 0 0 0 0]
[1 1 0 1 0 0]
[1 0 0 0 0 1]
[0 1 1 0 0 1]
[1 0 1 0 1 0]
</code></pre>

<p><strong>The resulting matrix:</strong></p>

<pre><code>[0 0 0 1 1 1]
[1 0 0 0 0 0]
[0 0 0 0 0 0]
[1 1 1 1 0 0]
[1 1 1 1 1 1]
[0 1 1 1 1 1]
[1 1 1 1 1 0]
</code></pre>

<p>I implement an algorithm, it works, but for large arrays it is not efficient.</p>

<pre><code>def beetween(Q):
    for client in range(len(Q)):
        idStart = findIdStart(Q, client)
        idEnd = findIdEnd(Q, client)
        if idStart != idEnd and idStart &gt; -1 and idEnd &gt; -1:
             for i in range(idStart, idEnd):
                  Q[client][i] = 1
     return Q

def findIdStart(Q, client):
    if Q.ndim &gt; 1:
        l, c = np.array(Q).shape
        for product in range (0, c):
            if Q[client][product] == 1:
                return product
    else:
        idProduct = 1
        Qtemp = Q[client]
        if Qtemp[idProduct] == 1:
            return idProduct
    return -1

def findIdEnd(Q, client):
    if Q.ndim &gt; 1:
        l, c = np.array(Q).shape
        Qtemp = Q[client]
        for product in range(0,c):
            idProduct = (c-1)-product
            if Qtemp[idProduct]==1:
                return idProduct
    else:
        idProduct = 1
        Qtemp = Q[client]
        if Qtemp[idProduct] == 1:
            return idProduct
    return -1
</code></pre>

<p>I'm trying to build a more optimized version, but I'm not having success:</p>

<pre><code>def beetween(Q):
    l, c = np.shape(Q)
    minIndex = Q.argmax(axis=1)
    maxIndex = c-(np.fliplr(Q).argmax(axis=1))
    Q = np.zeros(shape=(l,c)).astype(np.int)
    for i in range(l):
        Q[i, minIndex[i]:maxIndex[i]] = 1
    return Q
</code></pre>

<p><strong>Original matrix:</strong></p>

<pre><code>[0 0 0 1 0 1]
[1 0 0 0 0 0]
[0 0 0 0 0 0]
[1 1 0 1 0 0]
[1 0 0 0 0 1]
[0 1 1 0 0 1]
[1 0 1 0 1 0]
</code></pre>

<p><strong>Wrong Result</strong></p>

<pre><code>[0 0 0 1 1 1] # OK
[1 0 0 0 0 0] # OK
[1 1 1 1 1 1] # wrong
[1 1 1 1 0 0] # OK
[1 1 1 1 1 1] # OK
[0 1 1 1 1 1] # OK
[1 1 1 1 1 0] # OK
</code></pre>

<p>Can anybody suggest another simple solution to this problem?</p>

<p>Thanks.</p>

<p>The function below looks at a single row and fills 1s between other 1s if they exist.  It assumes that the array contains only 0s and 1s.</p>

<pre><code>import numpy as np

def ones_row(row):
    if np.sum(row) &gt;= 2:  # Otherwise, not enough 1s
        inds = np.where(row == 1)[0]
        row[inds[0]:inds[-1]] = 1
    return row
</code></pre>

<p>Now you can process your entire array with </p>

<pre><code>for jj in range(len(Q)):
    Q[jj] = ones_row(Q[jj])
</code></pre>

python arrays numpy matrix