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

时间:2012-06-28 16:56:15

标签: python numpy

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

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

4 个答案:

答案 0 :(得分: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 :(得分: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放在您创建的元组中的那些位置。

答案 2 :(得分: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会有效,就像阵列碰巧有这么少的尺寸而你实际上并不想要切片一样(但你不知道你不想提前切片。

答案 3 :(得分:0)

您还可以使用省略号来替换重复的冒号。 有关示例,请参阅answerHow do you use the ellipsis slicing syntax in Python?