我知道如何取x[:,:,:,:,j,:]
(取第 4 个维度的第 j 个切片)。
如果维度在运行时已知并且不是已知常数,是否有办法做同样的事情?
这样做的一种选择是以编程方式构建切片:
slicing = (slice(None),) * 4 + (j,) + (slice(None),)
另一种方法是使用numpy.take()
or 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]])
您可以使用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
例子:
>>> 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
您创建的元组中的那些位置。
如果一切都是在运行时决定的,你可以这样做:
# 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
,例如数组恰好具有如此少的维度以至于您实际上不想对其进行切片(但您不知道您不想将其切片时间)。