There are many times when you want to retrieve non-contiguous elements
>>> a = np.array([1,2,3,4])
>>> indices = [0,2]
>>> a[indices]
array([1,3])
Useful when you want to replace elements
>>> a = np.array([1,2,3,4])
>>> indices = [0,1,3,2]
>>> a[indices]
array([1, 2, 4, 3])
Note that if you pass set instead of list, an error will occur or unexpected behavior will occur. Be especially careful when using multidimensional arrays.
>>> a = np.array([[1,2,3],[3,4,5],[5,6,7]])
>>> a
array([[1, 2, 3],
[3, 4, 5],
[5, 6, 7]])
>>> indices = [0,2]
>>> a[indices]
array([[1, 2, 3],
[5, 6, 7]])
>>> indices = (0,2)
>>> a[indices]
3
Recommended Posts