Get the ith slice of the kth dimension in a numpy array

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

# ... 
elif k == 5:
    b = a[:, :, :, :, :, i, ...]
# ...
+6
source share
5 answers
b = a[(slice(None),) * k + (i,)]

Create an indexing tuple manually.

As stated in the Python link , the form expression

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

converted to

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

We can achieve the same effect by creating this tuple directly, instead of using notation for slicing. (There's a small caveat that building a tuple directly creates a[(i,)]instead a[i]for k=0, but NumPy treats them the same way for scalar i.)

+11

, k dim, 2 dim

a.take(i,axis=k)
+3

, :, :, :, :, :, i, ..., a. , (.. (:,) * k k ). " " colon = slice(None). b = a[(colon,) * k + (i,)], a i th k - .

, :

def nDimSlice(a, k, i):
    colon = slice(None)
    return a[(colon,) * k + (i,)]
+1

, , :

def put_at(inds, axis=-1, slc=(slice(None),)):
    return (axis<0)*(Ellipsis,) + axis*slc + (inds,) + (-1-axis)*slc

a[put_at(ind_list,axis=axis)]

ind_list , , - .

.

+1

, *, , k- :

import numpy as np

def get_slice(arr, k, i):
    if k >= arr.ndim: #we need at least k dimensions (0 indexed)
        raise ValueError("arr is of lower dimension than {}".format(k))

    axes_reorder = list(range(arr.ndim)) #order of axes for transpose
    axes_reorder.remove(k) #remove original position of k
    axes_reorder.insert(0,k) #insert k at beginning of order

    return arr.transpose(axes_reorder)[i] #k is first axis now

.

* docs, .

0

Source: https://habr.com/ru/post/1015761/


All Articles