2

Say I have 2 arrays

X = np.array([1.,2.,3.,4.,5.,])
Y = np.array([6.,7.,8.,9.,10.,])

and I want to define an array that takes a value of say 1 wherever X < 3 or Y = 9 and takes a value of 0 everywhere else. I used

Z=[1 if i < 3 or j==9 else 0 for i in X and j in Y]
print(Z)

I expect an array that looks like

[1,1,0,1,0] 

but I got this error:

ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

3 Answers 3

2

Try this:

np.where((X < 3) | (Y == 9) , 1, 0)
Sign up to request clarification or add additional context in comments.

2 Comments

Oh maaaan, i did where but i just missed the parenthesis of each condition for the or statement, gave me an error, so i use logical_or!!!
Yeah, the need of parenthesis is a result of operator precedence.
1

You can use zip to iterate over X and Y in pairs:

Z=[1 if i < 3 or j==9 else 0 for i, j in zip(X, Y)]

Z becomes:

[1, 1, 0, 1, 0]

Comments

1

Use np.logical_or, much more numpy-ish, much faster:

print(np.logical_or(X<3,Y==9).astype(int).tolist())

Output:

[1, 1, 0, 1, 0]

I recommend this because it's fast.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.