2

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 Answer 1

2

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.  ]])
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, okay. I thought it could be achieved in a couple of lines or so.
There may be some easier way, but since you need to insert into the array. You need to reconstruct anew, and find the corresponding indices @syntheso

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.