numpy.isin(element, test_elements, assume_unique=False, invert=False)
[source]
Calculates element in test_elements
, broadcasting over element
only. Returns a boolean array of the same shape as element
that is True where an element of element
is in test_elements
and False otherwise.
Parameters: |
|
---|---|
Returns: |
|
See also
in1d
numpy.lib.arraysetops
isin
is an element-wise function version of the python keyword in
. isin(a, b)
is roughly equivalent to np.array([item in b for item in a])
if a
and b
are 1-D sequences.
element
and test_elements
are converted to arrays if they are not already. If test_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 in test_elements
. This is a consequence of the array
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.
>>> 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]]) >>> element[mask] array([2, 4])
The indices of the matched values can be obtained with nonzero
:
>>> np.nonzero(mask) (array([0, 1]), array([1, 0]))
The test can also be inverted:
>>> mask = np.isin(element, test_elements, invert=True) >>> mask array([[ True, False], [False, True]]) >>> 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]])
Casting the set to a list gives the expected result:
>>> np.isin(element, list(test_set)) array([[False, True], [ True, False]])
© 2005–2019 NumPy Developers
Licensed under the 3-clause BSD License.
https://docs.scipy.org/doc/numpy-1.17.0/reference/generated/numpy.isin.html