7

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

如果维度在运行时已知并且不是已知常数,是否有办法做同样的事情?

4

4 回答 4

10

这样做的一种选择是以编程方式构建切片:

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]])
于 2012-06-28T16:58:11.580 回答
7

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

于 2012-06-28T17:01:07.467 回答
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,例如数组恰好具有如此少的维度以至于您实际上不想对其进行切片(但您不知道您不想将其切片时间)。

于 2018-04-12T18:11:35.547 回答
0

您还可以使用省略号来替换重复的冒号。查看如何在 Python 中使用省略号切片语法的答案例如。

于 2012-09-16T03:18:46.440 回答