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

2024-04-26 22:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果维度在运行时是已知的,而不是已知的常量,是否有方法执行相同的操作?


Tags: 方法常量
3条回答

如果一切都是在运行时决定的,您可以:

# 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,它将工作,就像数组的维度太少,以至于您实际上不想对其进行切片(但您不知道您不想提前对其进行切片)一样。

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

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

您可以使用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放在您创建的元组中的那些位置。

相关问题 更多 >