Python:给定维度索引,提取多维数组的一个切片

7

我知道如何使用x[:,:,:,:,j,:]来获取第4个维度上的第j个切片。

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


1
在形式上使用x[something]进行索引,等同于调用对象的__getitem__方法。例如,您上面的代码等同于将元组(slice(None), slice(None), slice(None), slice(None), j, slice(None))传递给x.__getitem__() - Joel Cornett
1
@JoelCornett:为什么要使用__getitem __()?相比于[]有什么优势吗? - Sven Marnach
@SvenMarnach:我不会这样做,只是觉得OP从理解这个概念中受益匪浅。如果他意识到这只是将参数传递给函数的问题,那么他的问题的答案就是微不足道的。 - Joel Cornett
@JoelCornett:啊,明白了。 - Sven Marnach
4个回答

10

有一种方法是通过编程构建切片:

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]])

1
你如何使用“切片”从“x”中提取某些内容? - Jason S

7
您可以在运行时使用“切片”函数,并按照适当的变量列表进行调用,如下所示:

切片 函数可帮助您完成此操作。

# 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


1
如果所有内容都在运行时决定,你可以这样做:
# 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(例如数组的维度很少,实际上不需要切片,但您事先不知道),它仍将起作用。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接