python - Numpy 按元素进行运算

标签 python performance numpy vectorization elementwise-operations

假设我有一个长度为 n 的列向量 y,并且有一个大小为 n*m 的矩阵 X。我想检查 y 中的每个元素 i,该元素是否位于 X 中的相应行中。最有效的方法是什么?

例如:

y = [1,2,3,4].T

X =[[1, 2, 3],[3, 4, 5],[4, 3, 2],[2, 2, 2]]

那么输出应该是

[1, 0, 1, 0] or [True, False, True, False] 

哪个更容易。

当然,我们可以使用 for 循环来迭代 y 和 X,但是有没有更有效的方法来做到这一点?

最佳答案

使用 broadcasting 的矢量化方法-

((X == y[:,None]).any(1)).astype(int)

示例运行 -

In [41]: X        # Input 1
Out[41]: 
array([[1, 2, 3],
       [3, 4, 5],
       [4, 3, 2],
       [2, 2, 2]])

In [42]: y        # Input 2
Out[42]: array([1, 2, 3, 4])

In [43]: X == y[:,None] # Broadcasted  comparison
Out[43]: 
array([[ True, False, False],
       [False, False, False],
       [False,  True, False],
       [False, False, False]], dtype=bool)

In [44]: (X == y[:,None]).any(1) # Check for any match along each row
Out[44]: array([ True, False,  True, False], dtype=bool)

In [45]: ((X == y[:,None]).any(1)).astype(int) # Convert to 1s and 0s
Out[45]: array([1, 0, 1, 0])

关于python - Numpy 按元素进行运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40175327/

相关文章:

android - 适用于 Android 的纯 C++ 应用程序及其性能

c - 未对齐数据的性能损失

python - numpy:通过引用传递对自身不起作用

python - 如何区分 numpy 数组和 Python 的内置对象

Python Scikit Learn : 'argument 1 must be a unicode character, 不是列表

python - 为什么 Matplotlib 不将图像读取为灰度?

python - 对 .pyd 文件进行逆向工程有多难?

python - 读取特定输入的文件 python

c - OpenMP for 循环

python - 为什么 statsmodels 的相关和自相关函数在 Python 中给出不同的结果?