How to get the values from a NumPy array using multiple indices
Question:
I have a NumPy array that looks like this:
arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])
How can I get multiple values from this array by index?
For example, how can I get the values at the index positions 1, 4, and 5?
I was trying something like this, which is incorrect:
arr[1, 4, 5]
Answers:
Try like this:
>>> arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])
>>> arr[[1,4,5]]
array([ 200.42, 34.55, 1.12])
And for multidimensional arrays:
>>> arr = np.arange(9).reshape(3,3)
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> arr[[0, 1, 1], [1, 0, 2]]
array([1, 3, 5])
you were close
>>> print arr[[1,4,5]]
[ 200.42 34.55 1.12]
Another solution is to use np.take
as specified in https://numpy.org/doc/stable/reference/generated/numpy.take.html
a = [4, 3, 5, 7, 6, 8]
indices = [0, 1, 4]
np.take(a, indices)
# array([4, 3, 6])
If you want to use multiple scalar and indices to slice a numpy array, you can use np.r_
to concat the indices first:
arr = np.array(range(100))
out = arr[np.r_[1,4,5,10:20,slice(40,50)]]
print(out)
[ 1 4 5 10 11 12 13 14 15 16 17 18 19 40 41 42 43 44 45 46 47 48 49]
I have a NumPy array that looks like this:
arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])
How can I get multiple values from this array by index?
For example, how can I get the values at the index positions 1, 4, and 5?
I was trying something like this, which is incorrect:
arr[1, 4, 5]
Try like this:
>>> arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])
>>> arr[[1,4,5]]
array([ 200.42, 34.55, 1.12])
And for multidimensional arrays:
>>> arr = np.arange(9).reshape(3,3)
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> arr[[0, 1, 1], [1, 0, 2]]
array([1, 3, 5])
you were close
>>> print arr[[1,4,5]]
[ 200.42 34.55 1.12]
Another solution is to use np.take
as specified in https://numpy.org/doc/stable/reference/generated/numpy.take.html
a = [4, 3, 5, 7, 6, 8]
indices = [0, 1, 4]
np.take(a, indices)
# array([4, 3, 6])
If you want to use multiple scalar and indices to slice a numpy array, you can use np.r_
to concat the indices first:
arr = np.array(range(100))
out = arr[np.r_[1,4,5,10:20,slice(40,50)]]
print(out)
[ 1 4 5 10 11 12 13 14 15 16 17 18 19 40 41 42 43 44 45 46 47 48 49]