python:在给定维度索引的情况下提取多维数组的一个切片

Jas*_*n S 7 python numpy

我知道如何采取x[:,:,:,:,j,:](采取第4维的第j个切片).

如果维度在运行时已知,并且不是已知的常量,是否有办法做同样的事情?

Sve*_*ach 10

这样做的一个选择是以编程方式构造切片:

slicing = (slice(None),) * 4 + (j,) + (slice(None),)
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用numpy.take()ndarray.take():

>>> a = numpy.array([[1, 2], [3, 4]])
>>> a.take((1,), axis=0)
array([[3, 4]])
>>> a.take((1,), axis=1)
array([[2],
       [4]])
Run Code Online (Sandbox Code Playgroud)


Dha*_*ara 7

您可以使用slice函数并在运行时使用适当的变量列表调用它,如下所示:

# Store the variables that represent the slice in a list/tuple
# Make a slice with the unzipped tuple using the slice() command
# Use the slice on your array
Run Code Online (Sandbox Code Playgroud)

例:

>>> from numpy import *
>>> a = (1, 2, 3)
>>> b = arange(27).reshape(3, 3, 3)
>>> s = slice(*a)
>>> b[s]
array([[[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])
Run Code Online (Sandbox Code Playgroud)

这与:

>>> b[1:2:3]
array([[[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])
Run Code Online (Sandbox Code Playgroud)

最后,相当于:在通常的表示法中没有指定2之间的任何东西就是放入None你创建的元组中的那些位置.