[英]comparing vector to each element of another vector with numpy
I have 2 vectors, I would like to compute a matrix where the i'th row is the first vector compared to the i'th element of the second vector.我有 2 个向量,我想计算一个矩阵,其中第 i 行是第一个向量,与第二个向量的第 i 个元素相比。 This code does that:
这段代码是这样做的:
a1 = np.array([1, 2, 3])
a2 = np.array([1, 2, 3])
print(np.array([a1 > e for e in a2]))
where we get:我们得到:
[[False True True]
[False False True]
[False False False]]
I want to have the same behavior but done efficiently with "numpy magic".我想拥有相同的行为,但使用“numpy magic”高效完成。 How can I do this?
我怎样才能做到这一点?
You can broadcast the function by making one of the arrays have one singleton dimension:您可以通过使数组之一具有一个单一维度来广播该函数:
In [1]: import numpy as np
In [2]: a1 = np.array([1, 2, 3])
...: a2 = np.array([1, 2, 3])[:,None]
In [3]: a1>a2
Out[3]:
array([[False, True, True],
[False, False, True],
[False, False, False]])
The np.meshgrid
(see documentation ) is useful for constructing 2-d arrays, where each of two 1d vectors is broadcast across the number of elements of the other. np.meshgrid
(参见文档)对于构建np.meshgrid
数组很有用,其中两个一维向量中的每一个都在另一个元素的数量上广播。 It might be easier to see what is going on if the arrays have different elements and sizes:如果数组具有不同的元素和大小,可能更容易看到发生了什么:
>>> a1 = np.array([1,5,7])
>>> a2 = np.array([2,3,4,5])
>>> a1_2d, a2_2d = np.meshgrid(a1, a2)
>>> a1_2d
array([[1, 5, 7],
[1, 5, 7],
[1, 5, 7],
[1, 5, 7]])
>>> a2_2d
array([[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]])
Note that these two vectors have been broadcast across different dimensions.请注意,这两个向量已在不同维度上广播。
They can then be compared element-by-element using the >
operator to give an array of booleans.然后可以使用
>
运算符逐个比较它们以给出布尔数组。
>>> a1_2d > a2_2d
array([[False, True, True],
[False, True, True],
[False, True, True],
[False, False, True]])
Or going back to your original vectors, this gives:或者回到你的原始向量,这给出:
array([[False, True, True],
[False, False, True],
[False, False, False]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.