Indexing a matrix by a column vector
<p>I have a matrix M of size m x n, and column vector of m x 1.
For each of m rows, I need to pickup the index corresponding to the value in the column vector minus 1. Thus, giving me answer m x 1. How can I do this?</p>

<pre><code>zb=a1.a3[np.arange(a1.z3.shape[0]),a1.train_labels-1]

zb.shape
Out[72]: (4000, 4000)

a1.z3.shape
Out[73]: (4000, 26)

a1.train_labels.shape
Out[74]: (4000, 1)

a1.train_labels.head()
Out[75]: 
      22
1618  25
2330   1
1651  17
133   17
2360   5


#my column vector a1.train_labels is shuffled. I don't want to unshuffle it.
</code></pre>

<p>If your 2d array is <em>M</em>, and indices are a 1d array <code>v</code>, then you can use</p>

<pre><code>M[np.arange(len(v)), v - 1]
</code></pre>

<p>For example:</p>

<pre><code>In [14]: M = np.array([[1, 2], [3, 4]])

In [15]: v = np.array([2, 1])

In [16]: M[np.arange(len(v)), v - 1]
Out[16]: array([2, 3])
</code></pre>

python numpy