Reputation: 9806
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?
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.
Upvotes: 1
Views: 64
Reputation: 76297
If your 2d array is M, and indices are a 1d array v
, then you can use
M[np.arange(len(v)), v - 1]
For example:
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])
Upvotes: 1