0

I have a 2D NumPy array filled with zeroes (placeholder values). I would like to add a 1D array filled with ones and zeroes to a part of it. eg.

  • 2D array:

    array([[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]])
    
  • 1D array:

    array([1, 0, 1])
    

Desired end product: I want the array starting in position [2, 1]

array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 1],
       [0, 0, 0, 0, 0]]) 

Or an insertion in any other position it could reasonably fit in. I have tried to do it with boolean masks but have not had any luck creating one in the correct shape. I have also tried flattening the 2D array, but couldn't figure out how to replace the values in the correct space.

3
  • 1
    Have you tried indexing the 2d array with arr[1,2:5]? Commented Aug 10, 2021 at 15:11
  • next time at least provide us with the correct format for the arrays (i.e. [[11,2],....] , ) , please Commented Aug 10, 2021 at 15:27
  • Can't believe I tried boolean masks but forgot about fancy indexing. Thanks! Commented Aug 10, 2021 at 15:29

1 Answer 1

1

You can indeed flatten the array and create a sequence of positions where you will insert your 1D array segment:

>>> pos = [1, 2]
>>> start = x.shape[1]*pos[0] + pos[1]
>>> seq = start + np.arange(len(segment))

>>> seq
array([7, 8, 9])

Then, you can either index the flattened array:

>>> x_f = x.flatten()
>>> x_f[seq] = segment
>>> x_f.reshape(x.shape)
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 1],
       [0, 0, 0, 0, 0]])

Alternatively, you can np.ravel_multi_index to get seq and apply np.unravel_index on it.

>>> seq = np.arange(len(segment)) + np.ravel_multi_index(pos, x.shape)
array([7, 8, 9])

>>> indices = np.unravel_index(seq, x.shape)
(array([1, 1, 1]), array([2, 3, 4]))

>>> x[indices] = segment
>>> x
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 1],
       [0, 0, 0, 0, 0]])
Sign up to request clarification or add additional context in comments.

Comments

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.