简体   繁体   中英

From a 1-dim array of bits obtain a particular 2-dim array of sequences of ones [Python]

I am using Python and I need to find the most efficient way to perform the following task.

Task: Given any 1-dimensional array v of zeros and ones, denote by k >=0 the number of subsequences of all ones of v .

I need to obtain from v a 2-dimensional array w such that:
1) shape(w)=(k,len(v)),
2) for every i=1,..,k, the i-th row of "w" is an array of all zeros except for the i-th subsequence of all ones of v .

Let me make an example: suppose $v$ is the array

v=[0,1,1,0,0,1,0,1,1,1]

Then k=3 and w should be the array

w=[[0,1,1,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,1,1,1]]

It is possible to write the code to perform this task in many ways, for example:

import numpy as np

start=[]
end=[]
for ii in range(len(v)-1):
    if (v[ii:ii+2]==[0,1]).all():
        start.append(ii)
    if (v[ii:ii+2]==[1,0]).all():
        end.append(ii)
if len(start)>len(end):
    end.append(len(v)-1)

w=np.zeros((len(start),len(v)))
for jj in range(len(start)):
    w[jj,start[jj]+1:end[jj]+1]=np.ones(end[jj]-start[jj])

But I need to perform this task on a very big array v and this task is part of a function which then undergoes minimization.. so I need it to be as efficient and fast as possible..

So in conclusion my question is: what is the most computationally efficient way to perform it in Python?

Here's one vectorized way -

def expand_islands2D(v):
    # Get start, stop of 1s islands
    v1 = np.r_[0,v,0]
    idx = np.flatnonzero(v1[:-1] != v1[1:])
    s0,s1 = idx[::2],idx[1::2]

    # Initialize 1D id array  of size same as expected o/p and has 
    # starts and stops assigned as 1s and -1s, so that a final cumsum
    # gives us the desired o/p
    N,M = len(s0),len(v)
    out = np.zeros(N*M,dtype=int)

    # Setup starts with 1s
    r = np.arange(N)*M
    out[s0+r] = 1

    # Setup stops with -1s
    if s1[-1] == M:
        out[s1[:-1]+r[:-1]] = -1
    else:
        out[s1+r] = -1

    # Final cumsum on ID array
    out2D = out.cumsum().reshape(N,-1)
    return N, out2D 

Sample run -

In [105]: v
Out[105]: array([0, 1, 1, 0, 0, 1, 0, 1, 1, 1])

In [106]: k,out2D = expand_islands2D(v)

In [107]: k # number of islands
Out[107]: 3

In [108]: out2D # 2d output with 1s islands on different rows
Out[108]: 
array([[0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM