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

标签 python arrays numpy operators

如何对 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/

相关文章:

javascript - 使用 ajax 和 django 根据用户提供的值进行过滤

python - 使用 urllib 2 捕获错误 60(超时)

python - 如何使用单个 API 调用扫描 HappyBase 中的行集?

python - 从 2 个 1D 数组生成 2D 数组的矢量化方法

python - 在Python中不使用 'for'循环滑动搜索窗口

python - 在 2d numpy 数组列上计算成对 t 检验

python - 如何动态定义scrapy项目

c - 从 Swift 访问 char** 结果

javascript - 如何存储和打印 document.getElementsByClassName 中的元素?

来自 genfromtxt 的 Python 2D numpy 数组