Numpy element-wise in operation

对着背影说爱祢 提交于 2019-12-02 05:46:45

Vectorized approach using broadcasting -

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

Sample run -

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])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!