AKUKamil
AKUKamil

Reputation: 11

Changing numpy array with array of indices

I have an array in numpy: A=np.zeros((5,10)) and I want to change one value in each row with ones according to another array N=np.array([7, 2, 9, 4, 5])

like: A[:,N]=1;

0   0   0   0   0   1   0   0   0   0
0   0   1   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   1
0   0   0   0   1   0   0   0   0   0
0   0   0   0   0   1   0   0   0   0

How can I do that?

Upvotes: 1

Views: 69

Answers (1)

shx2
shx2

Reputation: 64298

Since you want to set a single element per row, you need to fancy-index the first axis using arange(5). this can be thought of as setting indices (I0[0], N[0])=(0,7), (I0[1],N[1])=(1,2), ...

I0 = np.arange(A.shape[0])
A[I0, N] = 1
A
=> 
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.]])
A.nonzero()
=> (array([0, 1, 2, 3, 4]), array([7, 2, 9, 4, 5]))

Upvotes: 3

Related Questions