I have a 2d array:
a = np.random.randint(100, size=(6, 4))
[[72 76 40 11]
[48 82 6 87]
[53 24 25 99]
[ 7 94 82 90]
[28 81 10 9]
[94 99 67 58]]
And a 1d array:
idx = np.random.randint(4, size=6)
[0, 3, 2, 1, 0, 2]
Is it possible to index the 2d array so that the result is:
a[idx]
[72, 87, 25, 94, 28, 67]
Indexing a Two-dimensional Array To access elements in this array, use two indices. One for the row and the other for the column. Note that both the column and the row indices start with 0. So if I need to access the value '10,' use the index '3' for the row and index '1' for the column.
Two-dimensional (2D) arrays are indexed by two subscripts, one for the row and one for the column. Each element in the 2D array must by the same type, either a primitive type or object type.
Create a 2d array of appropriate size. Use a for loop to loop over your 1d array. Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.
Since you have the column indices, all you need are the row indices. You can generate those with arange
.
>>> a[np.arange(len(a)), idx]
array([72, 87, 25, 94, 28, 67])
Is there any way to get by this without arange
? It seems counterintuitive to me that something like
a[idx.reshape(-1,1)]
or
a[:,idx]
would not produce this result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With