在NumPy数组中搜索另一个NumPy数组

3

我需要找出一个numpy数组是否在另一个numpy数组内,但它似乎与python列表的工作方式不同。

我尝试在numpy文档和互联网上搜索此问题,但没有答案。

以下是一个例子:

import numpy as np

m1=np.array([[1,2,3],[5,3,4]])
m2=np.array([5,4,3])
m2 in m1
True
m3=[[1,2,3],[5,3,4]]
m4=[5,4,3]
m4 in m3
False

在numpy中,我得到了True,但是使用Python列表时,我得到了False。是否有任何numpy函数可以让这个工作?谢谢。

m3 中是否有拼写错误?你是不是想把 m3 = [[1, 2, 3], [5, 4, 3]] 替换为 m3 = [[1, 2, 3], [5, 3, 4]] - Bi Rico
1个回答

3
为了使列表具有与“in”相同的行为,您可以执行以下操作:
any(np.all(row == m2) for row in m1)

这段代码在Python中循环行,虽然不是最理想的方式,但应该可以工作。

为了理解numpy中in的含义,这里提供了一份描述in语义的说明来源于numpy邮件列表上的Robert Kern

It dates back to Numeric's semantics for bool(some_array), which would be True if any of the elements were nonzero. Just like any other iterable container in Python, x in y will essentially do

for row in y:
   if x == row:
       return True
return False

Iterate along the first axis of y and compare by boolean equality. In Numeric/numpy's case, this comparison is broadcasted. So that's why [3,6,4] works, because there is one row where 3 is in the first column. [4,2,345] doesn't work because the 4 and the 2 are not in those columns.

Probably, this should be considered a mistake during the transition to numpy's semantics of having bool(some_array) raise an exception. scalar in array should probably work as-is for an ND array, but there are several different possible semantics for array in array that should be explicitly spelled out, much like bool(some_array).


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接