Insert values between other values in numpy array

Viewed 83

Let's say I start with this array:

start_array = [[1.48, 1.79, 2.10, 2.80]
 [63, 60, 57,  60]]

I want to take the values in this second array:

second_array = np.array([2.3,3.42, 4.47])

and insert them in in between the values in the first row, with a 1 in another row to code that something occurred there. The remaining places should be filed with zeros.

Result:

result = np.array([[1.48, 1.79, 2.10, 2.3, 2.80, 3.42, 4.47],
                   [63., 60., 57., 0, 60., 0, 0],
                   [0, 0, 0, 1, 0, 1, 1]
                   ])
1 Answers

Here's a numpy based approach:

# flatten start, and searchsorted to see where to insert
start_array_view = start_array.ravel()
ixs = np.searchsorted(start_array_view, second_array) + np.arange(len(second_array))
# construct output array 
x,y = start_array.shape
out = np.zeros((x,y+len(ixs)))
# insert values from second array
z_pad = [0]*(len(ixs)*out.shape[0]-len(second_array))
out[:,ixs] = np.r_[second_array,z_pad ].reshape(out.shape[0],-1)
# insert values from start array
ar = np.arange(out.shape[1])
ixs_start = ar[~np.isin(ar, ixs)]
out[:,ixs_start] = start_array
# add indicator row
z = np.zeros(out.shape[1])
z[ixs] = 1
out = np.vstack([out,z])

print(out)
array([[ 1.48,  1.79,  2.1 ,  2.3 ,  2.8 ,  3.42,  4.47],
       [63.  , 60.  , 57.  ,  0.  , 60.  ,  0.  ,  0.  ],
       [ 0.  ,  0.  ,  0.  ,  1.  ,  0.  ,  1.  ,  1.  ]])
Related