Double AA
Double AA

Reputation: 5979

Comparing elements of numpy arrays in python

I want to compare two 1x3 arrays such as:

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

(output here is a 3x3x3 so output[x][y] is only a 1x3).

I'm getting an error that says:

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

Does that mean I need to do it like:

if output[y][x][0] == 150 and output[y][x][1] == 25 and output[y][x][2] == 75:

or is there a cleaner way to do this?

I'm using Python v2.6

Upvotes: 3

Views: 12064

Answers (4)

unutbu
unutbu

Reputation: 880627

The numpy way is to use np.allclose:

np.allclose(a,b)

Though for integers,

not (a-b).any()

is quicker.

Upvotes: 8

TorelTwiddler
TorelTwiddler

Reputation: 6166

you could try:

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

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

Upvotes: 0

SiggyF
SiggyF

Reputation: 23195

You should also get the message:

Use a.any() or a.all()

This means that you can do the following:

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

That is because the comparison of 2 arrays or an array with a list results in a boolean array. Something like:

array([ True,  True,  True], dtype=bool)

Upvotes: 5

jcomeau_ictx
jcomeau_ictx

Reputation: 38492

convert to a list:

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

Upvotes: 3

Related Questions