Find where a NumPy array is equal to any value in a list of values

前端 未结 3 1424
心在旅途
心在旅途 2020-12-18 21:19

I have an array of integers and want to find where that array is equal to any value in a list of multiple values.

This can easily be done by treating each value indi

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 21:46

    NumPy 0.13+

    As of NumPy v0.13, you can use np.isin, which works on multi-dimensional arrays:

    >>> 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]])
    

    NumPy pre-0.13

    The accepted answer with np.in1d works only with 1d arrays and requires reshaping for the desired result. This is good for versions of NumPy before v0.13.

提交回复
热议问题