Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the i-th slice of the k-th dimension in a numpy array

I have an n-dimensional numpy array, and I'd like to get the i-th slice of the k-th dimension. There must be something better than

# ... 
elif k == 5:
    b = a[:, :, :, :, :, i, ...]
# ...
like image 699
Nico Schlömer Avatar asked Mar 15 '17 18:03

Nico Schlömer


People also ask

How do you get the dimension of a NumPy array?

ndim to get the number of dimensions. Alternatively, we can use the shape attribute to get the size of each dimension and then use len() function for the number of dimensions. Use numpy. array() function to convert a list to a NumPy array and use one of the above two ways to get the number of dimensions.

How do I take slices from an NP array?

Slice Two-dimensional Numpy Arrays To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])


1 Answers

b = a[(slice(None),) * k + (i,)]

Construct the indexing tuple manually.

As documented in the Python language reference, an expression of the form

a[:, :, :, :, :, i]

is converted to

a[(slice(None), slice(None), slice(None), slice(None), slice(None), i)]

We can achieve the same effect by building that tuple directly instead of using slicing notation. (There's the minor caveat that building the tuple directly produces a[(i,)] instead of a[i] for k=0, but NumPy handles these the same for scalar i.)

like image 189
user2357112 supports Monica Avatar answered Sep 27 '22 22:09

user2357112 supports Monica