简体   繁体   English

numpy ndarray切片与数组

[英]Numpy ndarray slicing with arrays

I am having trouble understanding the reason behind a numpy broadcasting error when trying to slice an ndarray along separate dimensions using multiple slicing arrays. 当尝试使用多个切片数组沿单独的维度切片ndarray时,我无法理解numpy广播错误背后的原因。 I am trying to slice data ndarray (100, 306, 481) along the first and second dimensions using an index array picks eg, np.arange(2, 306, 3) and a boolean array mask , where mask.shape is (481,) of which 361 elements are True . 我正在尝试使用索引数组picks例如np.arange(2,306,3)和一个布尔数组mask (其中mask.shape为(481))沿第一和第二维将data ndarray(100,306,481)切片,),其中361个元素为True

data[:, picks, mask] returns data[:, picks, mask]返回

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (102,) (361,) IndexError:形状不匹配:索引数组不能与形状(102,)(361,)一起广播

However data[:, :, mask] , data[:, picks, :] , and data[:, :10, mask] work as expected. 但是data[:, :, mask]data[:, picks, :]data[:, :10, mask]正常工作。

How does broadcasting work in this case? 在这种情况下,广播如何工作? and what is a pythonic way of doing this? python方法是什么呢?

So 所以

data[:, :, mask]  => (100, 306, 361) 
data[:, :10, mask] => (100, 10, 361)
data[:, picks, :] => (100, 102, 481)

If picks had (361,) elements then 如果picks具有(361,)个元素,则

data[:, picks, mask] => (100, 361)  # I think :)

Think of picks matching np.where(mask) 想的picks匹配np.where(mask)

But to index in separate dimensions, picks has to be a column vector, so (102,1) broadcasts with (1, 361) to produce a (102,361) selection 但是要在不同维度上建立索引, picks必须是列向量,因此(102,1)用(1,361)广播以产生(102,361)选择

data[:, picks[:,None], mask] => (100, 102, 361) # again I need to test

So creating some test arrays: 因此,创建一些测试数组:

In [253]: data=np.ones((100,306,481))
In [254]: picks=np.arange(2,306,3)
In [255]: mask=np.zeros(481,bool)
In [256]: mask[:361]=True
In [257]: data[:, picks[:,None],mask].shape
Out[257]: (100, 102, 361)

the arange could be replaced with a slice 范围可以用切片代替

In [259]: data[:, 2::3, mask].shape
Out[259]: (100, 102, 361)

ix_ is handy in this case ix_在这种情况下很方便

In [268]: I,J=np.ix_(picks,mask)
In [269]: I.shape
Out[269]: (102, 1)
In [270]: J.shape
Out[270]: (1, 361)
In [271]: data[:,I,J].shape
Out[271]: (100, 102, 361)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM