Create an array with elements inserted without using np.insert

I have two arrays, let's say

n = [1,2,3,4,5,6,7,8,9]
nc = [3,0,2,0,1,2,0,0,0]

Nonzero elements in nc are ncz = [3,2,1,2]. Elements in n, the corresponding non-zero elements in nc, p = [1,3,5,6]. I need to create a new array with elements p[1:]inserted after ncz.cumsum()[:-1]+1ie after [4,6,7] Is there a way to do this without using np.insert or a for loop? Suppose I have such pairs of arrays. Can I do the same for each pair without using a loop? The resulting arrays can be zero to bring them into the same shape. The result will be[1, 2, 3, 4, 3, 5, 6, 5, 7, 6, 8, 9]

To do this using np.insert, one could do:

n = np.array([1,2,3,4,5,6,7,8,9])
nc = np.array([3,0,2,0,1,2,0,0,0])
p1 = n[nc.nonzero()][1:]
ncz1 = nc[nc.nonzero()][:-1].cumsum()
result = np.insert(n,ncz1+1,p1)

, , numpy, anano, anano .

0
1

- np.insert ( ), , 1d ,

np.insert(n, i, p1) :

In [688]: n
Out[688]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [689]: p1
Out[689]: array([13, 15, 16])
In [690]: i
Out[690]: array([4, 6, 7], dtype=int32)

, z :

In [691]: j=i+np.arange(len(i))
In [692]: z=np.zeros(len(n)+len(i),dtype=n.dtype)

- True, n go, False p1 .

In [693]: ind=np.ones(z.shape,bool)
In [694]: ind[j]=False
In [695]: ind
Out[695]: 
array([ True,  True,  True,  True, False,  True,  True, False,  True,
       False,  True,  True], dtype=bool)

:

In [696]: z[ind]=n
In [697]: z[~ind]=p1    # z[j]=p1 would also work
In [698]: z
Out[698]: array([ 1,  2,  3,  4, 13,  5,  6, 15,  7, 16,  8,  9])

, . . , numpy (, concatenate).

+1

Source: https://habr.com/ru/post/1649584/


All Articles