Juan Solana
Juan Solana

Reputation: 157

Indexing numpy matrix

So lets say I have a (4,10) array initialized to zeros, and I have an input array in the form [2,7,0,3]. The input array will modify the zeros matrix to look like this:

[[0,0,1,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,0,0],
 [1,0,0,0,0,0,0,0,0,0],
 [0,0,0,1,0,0,0,0,0,0]]

I know I can do that by looping through the input target and indexing the matrix array with something like matrix[i][target in input target], but I tried to do it without a loop doing something like: matrix[:, input_target] = 1, but that sets me the entire matrix to all 1. Apparently the way to do it is: matrix[range(input_target.shape[0]), input_target], the question is why this works and not using the colon ?

Thanks!

Upvotes: 0

Views: 76

Answers (1)

jpp
jpp

Reputation: 164623

You only wish to update one column for each row. Therefore, with advanced indexing you must explicitly provide those row identifiers:

A = np.zeros((4, 10))
A[np.arange(A.shape[0]), [2, 7, 0, 3]] = 1

Result:

array([[ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.]])

Using a colon for the row indexer will tell NumPy to update all rows for the specified columns:

A[:, [2, 7, 0, 3]] = 1

array([[ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.]])

Upvotes: 1

Related Questions