按照numpy的文档的把它做同样的事情为“花哨”的索引(索引阵列使用数组)。
的第二个参数np.take
必须是阵列状(阵列,列表,元组等),而不是一个对象slice
。你可以构建一个索引数组或列表,做你想要的片断:
a = np.arange(24).reshape(2, 3, 4)
np.take(a, slice(1, 4, 2), 2)
# TypeError: long() argument must be a string or a number, not 'slice'
np.take(a, range(1, 4, 2), 2)
# array([[[ 1, 3],
# [ 5, 7],
# [ 9, 11]],
# [[13, 15],
# [17, 19],
# [21, 23]]])
什么是指数的最好方式使用切片以及仅在运行时知道的轴的阵列?
我最喜欢做的是使用np.rollaxis
来使轴索引到第一个中,做我的索引,然后回滚到原来的位置。
例如,让我们说,我想沿着第3轴的三维阵列的奇数编号的切片:
sliced1 = a[:, :, 1::2]
如果我当时就想指定轴沿在运行时切片,我能做到这一点像这样的:
n = 2 # axis to slice along
sliced2 = np.rollaxis(np.rollaxis(a, n, 0)[1::2], 0, n + 1)
assert np.all(sliced1 == sliced2)
要解开一个班轮一点:
# roll the nth axis to the 0th position
np.rollaxis(a, n, 0)
# index odd-numbered slices along the 0th axis
np.rollaxis(a, n, 0)[1::2]
# roll the 0th axis back so that it lies before position n + 1 (note the '+ 1'!)
np.rollaxis(np.rollaxis(a, n, 0)[1::2], 0, n + 1)
请提供一个可运行的例子,以及你的前回复 – 2015-02-23 22:34:40
有些代码呢?因为我没有看到或理解你的问题,这对我来说很好[np.take(a,a [3:7])'这是通过数组索引数组。 – ljetibo 2015-02-23 22:34:48