Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify elements that belong to a set in a numpy array in python

Tags:

python

numpy

Say I have a numpy array

A = numpy.array([-1, 1, 2, -2, 3, -3])

I would like to get all numbers whose squares equal 1 or 9 (so the expected result is [1, -1, 3, -3]). I tried A[A**2 in [1, 9]] but got an error. Is there any built-in function to handle this simple task without doing loops? Thanks.

like image 879
Jiexing Wu Avatar asked Mar 03 '26 23:03

Jiexing Wu


2 Answers

numpy has a fucnction that does what you what called in1d:

import numpy

A = numpy.array([-1, 1, 2, -2, 3, -3])
mask = numpy.in1d(A**2, [1, 9])
print(mask)
# [ True  True False False  True  True]
print(A[mask])
# [-1  1  3 -3]
like image 90
Bi Rico Avatar answered Mar 05 '26 12:03

Bi Rico


You can use numpy.logical_or :

>>> import numpy as np
>>> A[np.logical_or(A**2==1,A**2==9)]
array([-1,  1,  3, -3])
like image 36
Mazdak Avatar answered Mar 05 '26 13:03

Mazdak



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!