python - 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
解决方案
import numpy as np
if np.any(array1 != array2) and not np.any(np.all(a == 0, axis=-1))
np.any(array1 != array2)
正在比较“大”3D 数组的每个元素。然而,这等同于val1
对val2
每个x
和进行比较y
。
另一个条件,np.any(np.all(a == 0, axis=-1))
稍微复杂一些。最内层np.all(a == 0, axis=-1)
创建一个 2D 布尔值数组。如果最后一个维度中的所有值都是 ,则每个值都设置为True
或False
取决于。外部条件检查 2D 数组中的任何值是否意味着存在等于的元素。0
True
array1[y, x]
[0, 0, 0]
推荐阅读
- d3.js - 放大缩小d3 js可折叠树
- mongodb - 聚合:嵌套文档中的分组日期(嵌套对象)
- excel - 带有 if/and/or 语句的 For 循环
- java - Spring data - 具有相同标识符的不同对象,即使对象相等
- python - Pygame 'pygame.Surface' 对象不可调用
- node.js - 将 8kHz mulaw 转换为 PCM 16kHz
- python - 为什么当我做子图时窗口正在切割我的桌子?
- python - PYTHON:带有本地文件夹文件调用的导入模块=错误
- javascript - 谷歌地图多个和重叠的复选框
- java - 在 Java 中的每个循环结束时等待?