Calvin Adams
Calvin Adams

Reputation: 1

How can I add a 1D array to a segment of a 2D array?

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.

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.

Upvotes: 0

Views: 72

Answers (1)

Ivan
Ivan

Reputation: 40638

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]])

Upvotes: 1

Related Questions