Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Index 3D array with index of last axis stored in 2D array

I have a ndarray of shape(z,y,x) containing values. I am trying to index this array with another ndarray of shape(y,x) that contains the z-index of the value I am interested in.

import numpy as np
val_arr = np.arange(27).reshape(3,3,3)
z_indices = np.array([[1,0,2],
                      [0,0,1],
                      [2,0,1]])

Since my arrays are rather large I tried to use np.take to avoid unnecessary copies of the array but just can't wrap my head around indexing 3-dimensional arrays with it.

How do I have to index val_arr with z_indices to get the values at the desired z-axis position? The expected outcome would be:

result_arr = np.array([[9,1,20],
                       [3,4,14],
                       [24,7,17]])
like image 292
Kersten Avatar asked Aug 19 '15 08:08

Kersten


People also ask

How do you find the index of an element in a 2D NumPy array?

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 do I select the last row of a NumPy array?

Slice One-dimensional Numpy Arrays If you to select the last element of the array, you can use index [11] , as you know that indexing in Python begins with [0] .

How do you access different rows of a multidimensional NumPy array?

In NumPy , it is very easy to access any rows of a multidimensional array. All we need to do is Slicing the array according to the given conditions. Whenever we need to perform analysis, slicing plays an important role.


1 Answers

If you have numpy >= 1.15.0 you could use numpy.take_along_axis. In your case:

result_array = numpy.take_along_axis(val_arr, z_indices.reshape((3,3,1)), axis=2)

That should give you the result you want in one neat line of code. Note the size of the indices array. It needs to have the same number of dimensions as your val_arr (and the same size in the first two dimensions).

like image 124
Roberto Avatar answered Nov 10 '22 03:11

Roberto