在Python中比较numpy数组的元素

3

我希望比较两个1x3的数组,例如:

if output[x][y] != [150,25,75]

这里的output是一个3x3x3的数组,因此output[x][y]只是1x3。

我收到了一个错误提示信息:

ValueError: The truth value of an array with more than one element is ambiguous. 

这是否意味着我需要这样做:
if output[y][x][0] == 150 and output[y][x][1] == 25 and output[y][x][2] == 75:

还有没有更简洁的方法来做这件事?

我正在使用Python v2.6。

4个回答

8

在numpy中,使用np.allclose方法:

np.allclose(a,b)

尽管对于整数,
not (a-b).any()

更快。

5

您还应该收到以下信息:

使用 a.any() 或 a.all()

这意味着您可以执行以下操作:

if (output[x][y] != [150,25,75]).all():

那是因为比较两个数组或者一个数组和一个列表会得到一个布尔数组。类似这样:
array([ True,  True,  True], dtype=bool)

1
我认为,对于 != 来说使用 .any 更合适,而对于 == 来说使用 .all 更合理。 - SiggyF

3

转换为列表:

if list(output[x][y]) != [150,25,75]

你也可以比较两个形状相同的数组,这将给你一个由True/False值组成的数组。 - Thomas K

0

你可以尝试:

a = output[x][y]
b = [150,25,75]

if not all([i == j for i,j in zip(a, b)]):

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接