我知道如何使用x[:,:,:,:,j,:]
来获取第4个维度上的第j个切片。
如果维度是在运行时确定的,并且不是已知常量,有没有办法做到同样的事情?
有一种方法是通过编程构建切片:
slicing = (slice(None),) * 4 + (j,) + (slice(None),)
另一种方法是使用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]])
切片 函数可帮助您完成此操作。
# 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]]])
最后,在通常的表示法中,两个:
之间未指定任何内容的等效方法是在您创建的元组中将这些位置放置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
(例如数组的维度很少,实际上不需要切片,但您事先不知道),它仍将起作用。
x[something]
进行索引,等同于调用对象的__getitem__
方法。例如,您上面的代码等同于将元组(slice(None), slice(None), slice(None), slice(None), j, slice(None))
传递给x.__getitem__()
。 - Joel Cornett__getitem __()
?相比于[]
有什么优势吗? - Sven Marnach