1

I have following indices

indices = array([[ 0,  0],
   [ 1,  1],
   [ 5,  3],
   [ 7,  9]])

I want to update a 2d numpy array with these indices as one

img = np.zeros((12,12), np.uint8)

I tried the following

img[indices] = 1
indices_x = indices[:, 0]
indices_y = indices[:, 1]
img[np.ix_(indices_x,indices_y)] = 1
2
  • 2
    Like this img[indices[:, 0], indices[:, 1]] = 1 Commented Jul 9, 2018 at 0:15
  • 1
    Thanks coldspeed. Cannot upvote because of low reputation Commented Jul 9, 2018 at 0:24

1 Answer 1

3

Try specifying the x and y indices separately.

In [0]: img[indices[:,0], indices[:,1]] = 3

In [1]: img
Out[1]: 
array([[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)

Alternatively, you can give a tuple or list:

In [2]: new_inds = tuple(zip(*indices))

In [3]: new_inds
Out[3]: ((0, 1, 5, 7), (0, 1, 3, 9))

In [4]: img[new_inds] = 4

In [5]: img
Out[5]: 
array([[4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
Sign up to request clarification or add additional context in comments.

2 Comments

One of these things is not like the other.
Thanks Oliver. Cannot upvote because of low reputation

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.