[英]comparing ndarray with values in 1D array to get a mask
I have two numpy array, 2D and 1D respectively. 我有两个numpy数组,分别是2D和1D。 I want to obtain a 2D binary mask where each element of the mask is true if it matches any of the element of 1D array. 我想获得一个2D二进制掩码,如果它与1D数组的任何元素匹配,则掩码的每个元素都为真。
Example 例
2D array
-----------
1 2 3
4 9 6
7 2 3
1D array
-----------
1,9,3
Expected output
---------------
True False True
False True False
False False True
Thanks 谢谢
You could use np.in1d
. 你可以使用np.in1d
。 Although np.in1d
returns a 1D array, you could simply reshape the result afterwards: 虽然np.in1d
返回一维数组,但您可以简单地重新np.in1d
结果:
In [174]: arr = np.array([[1,2,3],[4,9,6],[7,2,3]])
In [175]: bag = [1,9,3]
In [177]: np.in1d(arr, bag).reshape(arr.shape)
Out[177]:
array([[ True, False, True],
[False, True, False],
[False, False, True]], dtype=bool)
Note that in1d
is checking of the elements in arr
match any of the elements in bag
. 请注意, in1d
是检查arr
中的元素是否匹配bag
中的任何元素。 In contrast, arr == bag
tests if the elements of arr
equal the broadcasted elements of bag
element-wise . 与此相反, arr == bag
测试,如果的元素arr
等于的广播元件bag
逐元素 。 You can see the difference by permuting bag
: 您可以通过置换bag
来看到差异:
In [179]: arr == np.array([1,3,9])
Out[179]:
array([[ True, False, False],
[False, False, False],
[False, False, False]], dtype=bool)
In [180]: np.in1d(arr, [1,3,9]).reshape(arr.shape)
Out[180]:
array([[ True, False, True],
[False, True, False],
[False, False, True]], dtype=bool)
When you compare two arrays of unequal shape, NumPy tries to broadcast the two arrays to a single compatible shape before testing for equality. 当您比较两个不等形状的数组时,NumPy会尝试在测试相等性之前将两个数组广播为单个兼容的形状。 In this case, [1, 3, 9]
gets broadcasted to 在这种情况下, [1, 3, 9]
被广播
array([[1, 3, 9],
[1, 3, 9],
[1, 3, 9]])
since new axes are added on the left. 因为新的轴添加在左侧。 You can check the effect of broadcasting this way: 您可以通过这种方式检查广播效果:
In [181]: np.broadcast_arrays(arr, [1,3,9])
Out[185]:
[array([[1, 2, 3],
[4, 9, 6],
[7, 2, 3]]),
array([[1, 3, 9],
[1, 3, 9],
[1, 3, 9]])]
Once the two arrays are broadcasted up to a common shape, equality is tested element-wise , which means the values in corresponding locations are tested for equality. 一旦两个数组被广播到一个共同的形状,就会以元素方式测试相等性,这意味着对相应位置的值进行相等性测试。 In the top row, for example, the equality tests are 1 == 1
, 2 == 3
, 3 == 9
. 例如,在顶行中,等式测试是1 == 1
2 == 3
3 == 9
。 Hence, 因此,
In [179]: arr == np.array([1,3,9])
Out[179]:
array([[ True, False, False],
[False, False, False],
[False, False, False]], dtype=bool)
a = np.array([[1,2,3],[4,9,6],[7,2,3]])
b = np.array([1,9,3])
Have you tried this: 你试过这个:
print a == b
## array([[ True, False, True],
## [False, True, False],
## [False, False, True]], dtype=bool)
Look up broadcasting ( http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html ) to see why this works. 查看广播( http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html )以查看其工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.