希望有人可以向我解释以下我用numpy数组观察到的行为:
>>> import numpy as np
>>> data_block=np.zeros((26,480,1000))
>>> indices=np.arange(1000)
>>> indices.shape
(1000,)
>>> data_block[0,:,:].shape
(480, 1000) #fine and dandy
>>> data_block[0,:,indices].shape
(1000, 480) #what happened???? why the transpose????
>>> ind_slice=np.arange(300) # this is more what I really want.
>>> data_block[0,:,ind_slice].shape
(300, 480) # transpose again! arghhh!
我不了解这种转换行为,这对我想做的事情非常不方便.有人可以向我解释吗?获得data_block子集的另一种方法将是很大的收获.
解决方法:
您可以通过以下方式获得所需的结果:
>>> data_block[0,:,:][:,ind_slice].shape
(480L, 300L)
我承认我对numpy索引的工作原理没有完全的了解,但是the documentation似乎暗示了您遇到的麻烦:
Basic slicing with more than one non-: entry in the slicing tuple, acts like repeated application of slicing using a single non-: entry, where the non-: entries are successively taken (with all other non-: entries replaced by :). Thus,
x[ind1,...,ind2,:]
acts likex[ind1][...,ind2,:]
under basic slicing.Warning: The above is not true for advanced slicing.
和. . .
Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool).
因此,您通过使用ind_slice数组而不是常规切片进行索引来触发该行为.
文档本身说这种索引“可能有点让人难以理解”,因此我们俩在此都遇到麻烦也就不足为奇了:-).