2

This question has probably been asked somewhere before, but I couldn't find any after some search, hence posting here.

Say I have an array A and an index array idx. Let both the arrays be 2D for the time being.

import numpy as np

A = np.array([[3,3,4],
              [4,5,4],
              [3,4,5]])

idx = np.array([[1,1],
                [2,1],
                [1,0],
                [0,0]])

Now I want to replace the corresponding elements in A based on the indexes in idx to 0. Basically, I want to do A[idx]=0, which doesn't work.

How do I do this efficiently without running a loop?

Preferably, the proposed solution should be scalable to a higher dimensional (3D and above) arrays.

0

1 Answer 1

9

You can try:

A[idx[:,0], idx[:,1]]=0

output:

[[0 3 4]
 [0 0 4]
 [3 0 5]]

If you have excessive number of dimensions that you cannot hard code it, you can use:

A[tuple(idx.T)]=0
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.