2015-02-23 62 views
0

根据take 的numpy文档,它与“花哨”索引(使用数组索引数组)做同样的事情。但是,如果您需要沿给定轴的元素,则使用起来会更容易。numpy take不能使用分片索引

然而,与“幻想”或定期numpy的索引,使用切片作为指标似乎不支持:

In [319]: A = np.arange(20).reshape(4, 5) 

In [320]: A[..., 1:4] 
Out[320]: 
array([[ 1, 2, 3], 
     [ 6, 7, 8], 
     [11, 12, 13], 
     [16, 17, 18]]) 

In [321]: np.take(A, slice(1, 4), axis=-1) 
TypeError: long() argument must be a string or a number, not 'slice' 

什么是指数的最佳方式使用片沿轴的阵列只有在运行时知道?

+1

请提供一个可运行的例子,以及你的前回复 – 2015-02-23 22:34:40

+0

有些代码呢?因为我没有看到或理解你的问题,这对我来说很好[np.take(a,a [3:7])'这是通过数组索引数组。 – ljetibo 2015-02-23 22:34:48

回答

2

按照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) 
+0

酷!感谢您分享'np.rollaxis'技巧! – user2561747 2015-02-27 22:41:06

2

我认为你的意思是:

In [566]: np.take(A, slice(1,4)) 
... 
TypeError: int() argument must be a string or a number, not 'slice' 

作品就像喜欢np.insertnp.apply_along_axisA[1:4]

功能通过构建索引元组可以包括标量实现通用性,切片和数组。

ind = tuple([slice(1,4)]) # ndim terms to match array 
A[ind] 

np.tensordot是使用np.transpose移动动作轴到端(供np.dot)的一个例子。

另一个诀窍是将所有“过剩”轴倒塌为一个重塑。然后重新塑形。

+0

使用'np.r_'是一个不错的小巧解决方案。但是请记住用'A.shape [axis]'替换'None'来停止索引。并相应处理负面指标。 – user2561747 2015-02-27 23:08:17