On this page
numpy.isin
numpy.isin(element, test_elements, assume_unique=False, invert=False)
[source]-
Calculates
element in test_elements
, broadcasting overelement
only. Returns a boolean array of the same shape aselement
that is True where an element ofelement
is intest_elements
and False otherwise.Parameters: element : array_like
Input array.
test_elements : array_like
The values against which to test each value of
element
. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters.assume_unique : bool, optional
If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
invert : bool, optional
If True, the values in the returned array are inverted, as if calculating
element not in test_elements
. Default is False.np.isin(a, b, invert=True)
is equivalent to (but faster than)np.invert(np.isin(a, b))
.Returns: isin : ndarray, bool
Has the same shape as
element
. The valueselement[isin]
are intest_elements
.See also
in1d
- Flattened version of this function.
numpy.lib.arraysetops
- Module with a number of other functions for performing set operations on arrays.
Notes
isin
is an element-wise function version of the python keywordin
.isin(a, b)
is roughly equivalent tonp.array([item in b for item in a])
ifa
andb
are 1-D sequences.element
andtest_elements
are converted to arrays if they are not already. Iftest_elements
is a set (or other non-sequence collection) it will be converted to an object array with one element, rather than an array of the values contained intest_elements
. This is a consequence of thearray
constructor’s way of handling non-sequence collections. Converting the set to a list usually gives the desired behavior.New in version 1.13.0.
Examples
>>> element = 2*np.arange(4).reshape((2, 2)) >>> element array([[0, 2], [4, 6]]) >>> test_elements = [1, 2, 4, 8] >>> mask = np.isin(element, test_elements) >>> mask array([[ False, True], [ True, False]], dtype=bool) >>> element[mask] array([2, 4]) >>> mask = np.isin(element, test_elements, invert=True) >>> mask array([[ True, False], [ False, True]], dtype=bool) >>> element[mask] array([0, 6])
Because of how
array
handles sets, the following does not work as expected:>>> test_set = {1, 2, 4, 8} >>> np.isin(element, test_set) array([[ False, False], [ False, False]], dtype=bool)
Casting the set to a list gives the expected result:
>>> np.isin(element, list(test_set)) array([[ False, True], [ True, False]], dtype=bool)
© 2008–2017 NumPy Developers
Licensed under the NumPy License.
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isin.html