2

I want my array to pass two conditions. If I try to do this with just one I don't have any problems but if I'll give code two conditions python crashes. Here is my code:

import numpy as np
from collections import deque

queue = deque([], maxlen=10)

queue.appendleft(31)
queue.appendleft(32)
queue.appendleft(33)

cond1 = 35
cond2 = 30

A_1 = np.array(queue)

print(cond2 > A_1 < cond1)
# print(A_1 > 30)  # works
# array([ True,  True,  True], dtype=bool)

print(((cond2 > A_1 < cond1).sum() == A_1.size).astype(np.int))
# print(((A_1 > 30).sum() == A_1.size).astype(np.int))  # works
# 1
13
  • 1
    Numpy does not support shorthand operators. Please explicitly state them like this: (cond2 > A_1) & (A_1 < cond1) Commented May 27, 2018 at 7:20
  • 1
    Also, I don't understand what the second condition is doing, but it doesn't look correct to me. Commented May 27, 2018 at 7:21
  • 1
    I understand that, but I don't understand what ((cond2 > A_1 < cond1).sum() == A_1.size).astype(np.int) is trying to do. Commented May 27, 2018 at 7:24
  • 1
    Oh, okay, that makes sense. Anyway, the solution in my first comment should work, in case you didn't see it yet. Commented May 27, 2018 at 7:27
  • 1
    Well, yea, you switched it up: (cond1 > A_1) & (A_1 < cond2)... does that make more sense now? Commented May 27, 2018 at 7:30

2 Answers 2

4

Here is a random example:

import numpy as np

np.random.seed(123456)

array = np.array(np.random.randn(12))

print((array < 1) & (array > 0))

And numpy you have to put the conditions in parenthesis, and then use the & operator for an and condition. For an or condition you use the | operator and then follow the same format. This will get you an array of Boolean values.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answer. It doesn't work with my example. Everything returns False.
@Hsin This is just pseudo code. You may have zero examples in your code that return if you set the condition to the specific ones that I specified. If you set the conditions to the ones that YOU want, what does your code return?
1

It should be something like np.logical_and(A_1 < cond1, A_1 > cond2)

If you want to check if all the elements satisfy, just np.all(np.logical_and(A_1 < cond1, A_1 > cond2))

cond2 > A_1 < cond1 won't work as desired because cond2 > A_1 returns a bool array. Compare boolean values with cond1 is not wanted according to your description. To be explicit, one can use np.logical_and.

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.