gpt4 book ai didi

arrays - 在 numpy 数组中搜索 numpy 数组

转载 作者:行者123 更新时间:2023-12-01 15:24:15 24 4
gpt4 key购买 nike

我需要查找一个 numpy 数组是否在另一个 numpy 数组中,但它似乎与 python 列表的工作方式不同。我试图在 numpy 文档和互联网中搜索这个问题,但没有回答。这是一个例子:


将 numpy 导入为 np



m1=np.array([[1,2,3],[5,3,4]])
m2=np.array([5,4,3])
m1 中的 m2
真的
m3=[[1,2,3],[5,3,4]]
m4=[5,4,3]
立方米立方米
错误的

在 numpy 中我得到 True 但在 Python 列表中我得到 False。是否有任何 numpy 函数可以使这项工作正常进行?

谢谢。

最佳答案

要获得与列表的 in 相同的行为,您可以这样做:

any(np.all(row == m2) for row in m1)

这会在 python 中对行进行循环,这并不理想,但它应该可以工作。

要了解 numpy in 发生了什么,这里是对 in 语义的描述 from Robert Kern on the numpy mailing list :

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).

关于arrays - 在 numpy 数组中搜索 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13191887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com