Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy.where workaround

Tags:

python

numpy

For my arrays:
array([[ 1, 2, 3, 4, 5], #a
[ 1, 3, 5, 7, 9],
[ 5, 10, 15, 20, 25],
[ 2, 4, 6, 8, 5]])

and
array([[ 1, 2, 3, 4, 16], #b
[ 1, 3, 16, 7, 9],
[ 5, 16, 15, 20, 25],
[ 2, 4, 6, 8, 5]])

I try to get the result of np.where((a==5 and b==16)). I expect:

Out[1]: (array([0, 1], dtype=int64), array([4, 2], dtype=int64),

since that's where 5 and 16 share the same indices; but instead i get a

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

When i try np.where((a.all()==5 and b.any()==16)), i get

Out[1]: (array([], dtype=int64),)

Any ideas? Thanks in advance.

like image 942
Noob Saibot Avatar asked Feb 08 '26 05:02

Noob Saibot


1 Answers

You want to use & instead of and:

np.where((a==5) & (b==16))

When dealing with numpy arrays you want to use the bitwise operator instead of the logical and.

like image 156
JoshAdel Avatar answered Feb 12 '26 05:02

JoshAdel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!