1

I have faced a question which I can't deeply understand. Its bout numpy.where with concatenate operation.

There're no problem with: np.where(a<b), but concatenate: np.where(a<b and a<c) can't be use, because a<b and a<c are not correct operation, where a, b, c - NumPy arrays. Its need to use: a.any() or a.all().

enter image description here

But is possible to use bin concatenate &: (a<c) & (b<c) and np.where((a<c) & (b<c)).

My sample code is:

import numpy as np

a=np.random.rand(24)
b=np.random.rand(24)
print('numpy arr: a:',a,'numpy arr: b:',b,sep='\n',end='\n'*2)

x=np.where((a<.5) & (b<.5) & (a+b<.9))
print('np.where + &:',x,sep='\n',end='\n'*2)

x=np.where((a<.5) and (b<.5) and (a+b<.9))
print('np.where + and:',x,sep='\n',end='\n'*2)

Outs with error:

numpy arr: a:
[0.54537816 0.38319929 0.46888735 0.3094628  0.82972402 0.18391511
 0.42539084 0.94225313 0.084158   0.28709954 0.83255106 0.93719347
 0.8505356  0.97240065 0.04261917 0.680872   0.90600638 0.19259075
 0.97707041 0.71354481 0.85061694 0.37244139 0.86971696 0.16065248]
numpy arr: b:
[0.96636409 0.99881076 0.08200858 0.31301844 0.16029993 0.21851799
 0.96612466 0.2136599  0.83806977 0.88331435 0.49006737 0.96287388
 0.26380568 0.49451174 0.73109927 0.01291897 0.52652431 0.88284384
 0.46521207 0.32853427 0.70570596 0.04896036 0.19279199 0.79165465]

np.where + &:
(array([ 2,  3,  5, 21]),)

Traceback (most recent call last):
  File "/Users/tim/1.py", line 10, in <module>
    x=np.where((a<.5) and (b<.5) and (a+b<.9))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> 

Is it possible to use construction: np.where((a<c) & (b<c)), where a, b, c - NumPy arrays, or need to use numpy.any and numpy.all constructions?

Timur U
  • 415
  • 2
  • 14
  • Keep in mind that `where` just finds the `True` values in the argument. So your question is just about the `(a – hpaulj Oct 11 '20 at 18:09
  • Another key point is that `and` is a python operation that only works with simple True/False values. It's like the python `if`. If `x – hpaulj Oct 11 '20 at 19:33

0 Answers0