python - Combining logic statements AND in numpy array -


what way select elements when 2 conditions true in matrix? in r, possible combine vectors of booleans.

so i'm aiming for:

a = np.array([2,2,2,2,2]) < 3 , > 1  # < 3 & > 1 not work either 

evals to: valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all()

it should eval to:

array([true,true,true,true,true]) 

my workaround sum these boolean vectors , equate 2, there must better way. it?

you use &, eg:

x = np.arange(10) (x<8) & (x>2) 

gives

array([false, false, false,  true,  true,  true,  true,  true, false, false], dtype=bool) 

a few details:

  • this works because & shorthand numpy ufunc bitwise_and, bool type same logical_and. is, spelled out as
    bitwise_and(less(x,8), greater(x,2))
  • you need parentheses because in numpy & has higher precedence < , >
  • and not work because ambiguous numpy arrays, rather guess, numpy raise exception.

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -