How do I use a different index for each row in a numpy array?
<p>I have a NxM numpy array filled with zeros and a 1D numpy array of size N with random integers between 0 to M-1. As you can see the dimension of the array matches the number of rows in the matrix. Each element in the integer array means that at that given position in its corresponding row must be set to 1. For example:</p>

<pre><code># The matrix to be modified
a = np.zeros((2,10))
# Indices array of size N
indices = np.array([1,4])
# Indexing, the result must be
a = a[at indices per row]
print a

[[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]
</code></pre>

<p>I tried using the indexing <code>a[:,indices]</code> but this sets the same indices for each row, and this finally sets all the rows with ones. How can I set the given index to 1 <strong>per row</strong>?</p>

<p>Use <code>np.arange(N)</code> in order to address the rows and indices for columns:</p>

<pre><code>&gt;&gt;&gt; a[np.arange(2),indices] = 1
&gt;&gt;&gt; a
array([[ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.]])
</code></pre>

<p>Or:</p>

<pre><code>&gt;&gt;&gt; a[np.where(indices)+(indices,)] = 1
&gt;&gt;&gt; a
array([[ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.]])
</code></pre>

python arrays numpy matrix-indexing