1

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?

1
  • Which row of each column? Commented May 21, 2015 at 16:44

1 Answer 1

3

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]))
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.