[英]using boolean array for indexing in numpy for 2D arrays
I use boolean indexing to select elements from a numpy array as 我使用布尔索引从numpy数组中选择元素
x = y[t<tmax]
where ta numpy array with as many elements as y. 其中ta numpy数组具有与y一样多的元素。 My question is how can I do the same with 2D numpy arrays?
我的问题是如何对2D numpy数组执行相同操作? I tried
我试过了
x = y[t<tmax][t<tmax]
This does not seem to work however since it seems to select first the rows and then complains that the second selection has the wrong dimension. 但是,这似乎不起作用,因为它似乎先选择了行,然后抱怨第二个选择的维数错误。
IndexError: boolean index did not match indexed array along dimension 0; dimension is 50 but corresponding boolean dimension is 200
#
Here is an example 这是一个例子
print(x2D[x1D<3])
The second print statement produces an error similar to the error shown above. 第二个打印语句产生的错误类似于上面显示的错误。 I use
我用
[[1 2 3]
[1 2 3]]
I get 我懂了
[[1 2]
[1 2]]
but I want 但我想要
[[1 2] [1 2]]
In [28]: x1D = np.array([1,2,3], np.int32)
...: x2D = np.array([[1,2,3],[1,2,3],[1,2,3]], np.int32)
The 1d mask: 一维蒙版:
In [29]: x1D<3
Out[29]: array([ True, True, False])
applied to the 1d array (same size): 应用于一维数组(大小相同):
In [30]: x1D[_]
Out[30]: array([1, 2], dtype=int32)
applied to the 2d it selects 2 rows: 应用于2d,它选择2行:
In [31]: x2D[_29]
Out[31]:
array([[1, 2, 3],
[1, 2, 3]], dtype=int32)
It can be used again to select columns - but note the :
place holder for the row index: 可以再次使用它来选择列-但请注意
:
行索引的:
占位符:
In [32]: _[:, _29]
Out[32]:
array([[1, 2],
[1, 2]], dtype=int32)
If we generate an indexing array from that mask, we can do the indexing with one step: 如果我们从该掩码生成索引数组,则可以一步完成索引操作:
In [37]: idx = np.nonzero(x1D<3)
In [38]: idx
Out[38]: (array([0, 1]),)
In [39]: x2D[idx[0][:,None], idx[0]]
Out[39]:
array([[1, 2],
[1, 2]], dtype=int32)
An alternate way of writing this '2d' indexing: 编写此“ 2d”索引的另一种方法:
In [41]: x2D[ [[0],[1]], [[0,1]] ]
Out[41]:
array([[1, 2],
[1, 2]], dtype=int32)
ix_
is a convenient tool for tweaking the indexing dimensions: ix_
是用于调整索引尺寸的便捷工具:
In [42]: x2D[np.ix_(idx[0], idx[0])]
Out[42]:
array([[1, 2],
[1, 2]], dtype=int32)
Or passing the boolean mask to ix_
: 或将布尔型掩码传递给
ix_
:
In [44]: np.ix_(_29, _29)
Out[44]:
(array([[0],
[1]]), array([[0, 1]]))
In [45]: x2D[np.ix_(_29, _29)]
Out[45]:
array([[1, 2],
[1, 2]], dtype=int32)
Writing In[32]
so it's close to to your try: 写
In[32]
所以很接近您的尝试:
In [46]: x2D[x1D<3][:, x1D<3]
Out[46]:
array([[1, 2],
[1, 2]], dtype=int32)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.