首页 > 解决方案 > Comparing Numpy Arrays

问题描述

So I have two 2D numpy arrays of equal size, both obtained using the pygame.surfarray.array3d method on two different surfaces.

Each value in the array is also an array in the form [a, b, c] (so I basically have a 2D array with 1D elements).

I'd essentially like to compare the two based on the condition:

if any(val1 != val2) and all(val1 != [0, 0, 0]):
# can't be equal and val1 cant be [0, 0, 0] 

Is there any more efficient way of doing this without simply iterating through either array as shown below?

for y in range(len(array1)):
    for x in range(len(array1[y])):
        val1 = array1[y,x]; val2 = array[y,x]
        if any(val1 != val2) and all(val1 != [0, 0, 0]):
            # do something

标签: pythonarrayspython-3.xnumpypygame

解决方案


import numpy as np
if np.any(array1 != array2) and not np.any(np.all(a == 0, axis=-1))

np.any(array1 != array2)正在比较“大”3D 数组的每个元素。然而,这等同于val1val2每个x和进行比较y

另一个条件,np.any(np.all(a == 0, axis=-1))稍微复杂一些。最内层np.all(a == 0, axis=-1)创建一个 2D 布尔值数组。如果最后一个维度中的所有值都是 ,则每个值都设置为TrueFalse取决于。外部条件检查 2D 数组中的任何值是否意味着存在等于的元素。0Truearray1[y, x][0, 0, 0]


推荐阅读