python:提取给定维度索引的多维数组的一个片段

python:提取给定维度索引的多维数组的一个片段,python,numpy,Python,Numpy,我知道如何获取x[:,:,:,:,:,j,:](它获取维度4的第j个切片) 如果维度在运行时是已知的,而不是已知的常量,有没有办法做同样的事情?一种方法是通过编程方式构造切片: slicing = (slice(None),) * 4 + (j,) + (slice(None),) 另一种方法是使用numpy.take()或ndarray.take(): 您可以使用该函数,并在运行时使用适当的变量列表调用它,如下所示: # Store the variables that represent

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


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

一种方法是通过编程方式构造切片:

slicing = (slice(None),) * 4 + (j,) + (slice(None),)
另一种方法是使用
numpy.take()
ndarray.take()

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

# 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
例如:

>>> 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]]])
这与:

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

最后,在通常的表示法中不指定2之间的任何内容的等效方法是在创建的元组中的这些位置放置
None

您还可以使用省略号替换重复的冒号。
有关示例,请参见to。

如果一切都是在运行时决定的,则可以执行以下操作:

# Define the data (this could be measured at runtime)
data_shape = (3, 5, 7, 11, 13)
print('data_shape = {}'.format(data_shape))

# Pick which index to slice from which dimension (could also be decided at runtime)
slice_dim = len(data_shape)/2
slice_index = data_shape[slice_dim]/2
print('slice_dim = {} (data_shape[{}] = {}), slice_index = {}'.format(slice_dim, slice_dim, data_shape[slice_dim], slice_index))

# Make a data set for testing
data = arange(product(data_shape)).reshape(*data_shape)

# Slice the data
s = [slice_index if a == slice_dim else slice(None) for a in range(len(data_shape))]
d = data[s]
print('shape(data[s]) = {}, s = {}'.format(shape(d), s))

虽然这比
ndarray.take()
长,但如果
slice_index=None
,它会起作用,就像数组的维度太少,以至于您实际上不想对其进行切片(但您不知道您不想提前对其进行切片)。

x[something]的形式进行索引
与调用对象的
\uuu getitem\uuu
方法同义。例如,上面的代码相当于将元组
(slice(None)、slice(None)、slice(None)、slice(None)、j、slice(None))传递给
x?与
[]
相比,OP有什么优势?@SvenMarnach:我不会,我只是觉得OP会从理解这个概念中受益。如果他意识到这只是一个向函数传递参数的问题,那么他的问题的答案是微不足道的。@JoelCornett:啊,明白了。你如何使用
切片
x
中提取一些东西?
# Define the data (this could be measured at runtime)
data_shape = (3, 5, 7, 11, 13)
print('data_shape = {}'.format(data_shape))

# Pick which index to slice from which dimension (could also be decided at runtime)
slice_dim = len(data_shape)/2
slice_index = data_shape[slice_dim]/2
print('slice_dim = {} (data_shape[{}] = {}), slice_index = {}'.format(slice_dim, slice_dim, data_shape[slice_dim], slice_index))

# Make a data set for testing
data = arange(product(data_shape)).reshape(*data_shape)

# Slice the data
s = [slice_index if a == slice_dim else slice(None) for a in range(len(data_shape))]
d = data[s]
print('shape(data[s]) = {}, s = {}'.format(shape(d), s))