gpt4 book ai didi

python - numpy 数组的 "In"运算符?

转载 作者:太空狗 更新时间:2023-10-30 01:06:10 24 4
gpt4 key购买 nike

如何对 numpy 数组执行“in”操作?(如果给定的 numpy 数组中存在元素,则返回 True)

对于字符串、列表和字典,该功能直观易懂。

这是我在 numpy 数组上应用它时得到的结果

a
array([[[2, 3, 0],
[1, 0, 1]],

[[3, 2, 0],
[0, 1, 1]],

[[2, 2, 0],
[1, 1, 1]],

[[1, 3, 0],
[2, 0, 1]],

[[3, 1, 0],
[0, 2, 1]]])

b = [[3, 2, 0],
[0, 1, 1]]

b in a
True
#Aligned with the expectation

c = [[300, 200, 0],
[0, 100, 100]]

c in a
True
#Not quite what I expected

最佳答案

您可以比较输入数组的相等性,这将执行broadcasteda 中最后两个轴中每个位置的所有元素与第二个数组中相应位置的元素进行比较。这将产生一个 bool 匹配数组,我们在其中检查 ALL。匹配最后两个轴并最终检查 ANY匹配,就像这样 -

((a==b).all(axis=(1,2))).any()

样本运行

1) 输入:

In [68]: a
Out[68]:
array([[[2, 3, 0],
[1, 0, 1]],

[[3, 2, 0],
[0, 1, 1]],

[[2, 2, 0],
[1, 1, 1]],

[[1, 3, 0],
[2, 0, 1]],

[[3, 1, 0],
[0, 2, 1]]])

In [69]: b
Out[69]:
array([[3, 2, 0],
[0, 1, 1]])

2) 广播元素比较:

In [70]: a==b
Out[70]:
array([[[False, False, True],
[False, False, True]],

[[ True, True, True],
[ True, True, True]],

[[False, True, True],
[False, True, True]],

[[False, False, True],
[False, False, True]],

[[ True, False, True],
[ True, False, True]]], dtype=bool)

3) ALL 匹配最后两个轴,最后 ANY 匹配:

In [71]: (a==b).all(axis=(1,2))
Out[71]: array([False, True, False, False, False], dtype=bool)

In [72]: ((a==b).all(axis=(1,2))).any()
Out[72]: True

a 中的 c 执行类似的步骤 -

In [73]: c
Out[73]:
array([[300, 200, 0],
[ 0, 100, 100]])

In [74]: ((a==c).all(axis=(1,2))).any()
Out[74]: False

关于python - numpy 数组的 "In"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39452843/

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