[SciPy-User] Selecting elements in a numpy array by their indices contained in two arrays
Alexander Barth
barth.alexander at gmail.com
Tue Jun 27 03:30:44 EDT 2017
Dear Eric,
I think you can use numpy.ravel_multi_index for this.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel_multi_index.html
Here is an example:
In [10]: A = np.random.randn(4,4)
In [11]: A
Out[11]:
array([[ 1.9158152 , -0.69065018, 0.71567087, -1.31872821],
[ 1.00126163, 0.34461176, 0.30298258, -1.19507848],
[-0.14355935, 0.18827163, 0.78383867, -1.01362843],
[ 0.33303015, -1.49289243, -1.02713378, 0.24379566]])
In [12]: i = np.array([2,2,1,1])
In [13]: j = np.array([3,3,3,3])
In [16]: ij = np.ravel_multi_index((i,j),A.shape)
In [17]: ij
Out[17]: array([11, 11, 7, 7])
In [21]: A.flatten()[ij]
Out[21]: array([-1.01362843, -1.01362843, -1.19507848, -1.19507848])
In [23]: [A[i[l],j[l]] for l in range(len(i))]
Out[23]:
[-1.0136284267170597,
-1.0136284267170597,
-1.195078482610719,
-1.195078482610719]
I hope this helps,
Cheers,
Alex
More information about the SciPy-User
mailing list