numpy set value with indexes?

Viewed 36

I have a numpy like this:

arr = np.zeros((10, 10), dtype=np.int)

then I have a index list:

idxs = [1, 4, 7]

What I want to do is:

for index in idxs:
    arr[index, idxs] = 1

I want to know that do I have any better way to do this? Here, my better way means something like arr[idxs, idxs] = 1(I know this is wrong), at least, without for loop.

1 Answers
xs = np.zeros((10,10))
idx = np.array([1,4,7])


xs[idx[None].T,idx]=1
# or like some suggested in the comments,which is actually better

xs[np.ix_(idx,idx)]=1
Related