Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: How to index 2d array with 1d array?

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]
like image 305
MichaelSB Avatar asked Mar 06 '19 23:03

MichaelSB


People also ask

How are 2D NumPy arrays indexed?

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.

How is a 2D array indexed?

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.

How do I store a 1D array into a 2D array?

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.


2 Answers

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])
like image 105
cs95 Avatar answered Sep 24 '22 05:09

cs95


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.

like image 37
John Titor Avatar answered Sep 20 '22 05:09

John Titor