numpy.isin()

numpy.isin(element, test_elements, assume_unique=False, invert=False)
  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: 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 values element[isin] are in test_elements.


接下来看看例子

这个函数用来判断elements是否在test_elements中,返回一个与elements相同形状的布尔值。

>>> 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],  # 06 不在test_elements中,所以对应位置为False
       [ True,  False]])
>>> element[mask]   # 根据对应的位置的布尔值打印出值,是一维的 
array([2, 4])

默认情况下 invert=False,当它为True时。

>>> mask = np.isin(element, test_elements, invert=True)
>>> mask
array([[ True, False],  # 和上面例子不同的就是,不在test_elements中,对应位置为True
       [ False, True]])
>>> element[mask]
array([0, 6])

Note: test_element 必须为array, 如果是set或者其他形式,则test_elements就会被看作是一个整体。请看例子。

>>> test_set = {1, 2, 4, 8}
>>> np.isin(element, test_set)
array([[ False, False],
       [ False, False]])

从例子中就能看出来不同,所以要多加注意。当然test_elements不一定是一维的,也可以和element的形状相同。

>>> np.isin(element, list(test_set))
array([[ False,  True],
       [ True,  False]])

你可能感兴趣的:(numpy)