我刚才在查看代码的时候,看到了apply_along_axis
和apply_over_axis
函数的代码,研究它们是如何构建索引对象的。
我们来创建一个四维数组:
In [355]: b=np.ones((2,3,4,3),int)
使用列表 * 复制的方法,创建一个slices
列表
In [356]: ind=[slice(None)]*b.ndim
In [357]: b[ind].shape # same as b[:,:,:,:]
Out[357]: (2, 3, 4, 3)
In [358]: ind[2]=2 # replace one slice with index
In [359]: b[ind].shape # a slice, indexing on the third dim
Out[359]: (2, 3, 3)
或者使用你的示例。
In [361]: b = np.array([1,2,3],[4,5,6]) # missing []
...
TypeError: data type not understood
In [362]: b = np.array([[1,2,3],[4,5,6]])
In [366]: ind=[slice(None)]*b.ndim
In [367]: ind[0]=0
In [368]: a==b[ind]
Out[368]: array([ True, True, True], dtype=bool)
这种索引基本上与
np.take
相同,但是这个想法可以扩展到其他情况。
我不太明白你关于使用
:
的问题。请注意,在构建索引列表时,我使用
slice(None)
。解释器将所有索引
:
转换为
slice
对象:
[start:stop:step] => slice(start, stop, step)
。
通常您不需要使用
a[:]==b[0]
;
a==b[0]
就足够了。对于列表,
alist[:]
会创建一个副本,而对于数组,它什么也不做(除非在RHS上使用
a[:]=...
)。