Numpy逐元素运行 [英] Numpy element-wise in operation

查看:44
本文介绍了Numpy逐元素运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a column vector y with length n, and I have a matrix X of size n*m. I want to check for each element i in y, whether the element is in the corresponding row in X. What is the most efficient way of doing this?

例如:

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,但是有没有更有效的方法呢?

Of course we can use a for loop to iterate through both y and X, but is there any more efficient way of doing this?

推荐答案

使用 广播 -

((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])

这篇关于Numpy逐元素运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆