maxframe.tensor.isin#
- maxframe.tensor.isin(element: TileableType | ndarray, test_elements: TileableType | ndarray | list, assume_unique: bool = False, invert: bool = False)[源代码]#
计算 element in test_elements,仅对 element 进行广播。返回一个与 element 形状相同的布尔数组,当 element 中的元素在 test_elements 中时为 True,否则为 False。
- 参数:
element (array_like) -- 输入张量。
test_elements (array_like) -- 用于测试 element 中每个值的值。如果该参数是张量或 array_like,则会被展平。有关非类数组参数的行为,请参见说明。
assume_unique (bool, optional) -- 如果为 True,则假定输入张量都是唯一的,这可以加快计算速度。默认为 False。
invert (bool, optional) -- 如果为 True,则返回张量中的值会被反转,如同计算 element not in test_elements。默认为 False。
mt.isin(a, b, invert=True)等价于(但比)``mt.invert(mt.isin(a, b))`` 更快。
- 返回:
isin -- 与 element 具有相同的形状。element[isin] 的值在 test_elements 中。
- 返回类型:
Tensor, bool
参见
in1d此函数的展平版本。
备注
isin 是 Python 关键字 in 的逐元素函数版本。如果 a 和 b 是一维序列,则
isin(a, b)大致等价于mt.array([item in b for item in a])。element 和 test_elements 如果不是张量则会被转换为张量。如果 test_elements 是一个集合(或其他非序列集合),它将被转换为一个包含一个元素的对象张量,而不是包含 test_elements 中的值的张量。这是 tensor 构造函数处理非序列集合的方式造成的。将集合转换为列表通常能得到期望的行为。
示例
>>> import maxframe.tensor as mt
>>> element = 2*mt.arange(4).reshape((2, 2)) >>> element.execute() array([[0, 2], [4, 6]]) >>> test_elements = [1, 2, 4, 8] >>> mask = mt.isin(element, test_elements) >>> mask.execute() array([[ False, True], [ True, False]]) >>> element[mask].execute() array([2, 4]) >>> mask = mt.isin(element, test_elements, invert=True) >>> mask.execute() array([[ True, False], [ False, True]]) >>> element[mask] array([0, 6])
由于 array 处理集合的方式,以下操作不会按预期工作:
>>> test_set = {1, 2, 4, 8} >>> mt.isin(element, test_set).execute() array([[ False, False], [ False, False]])
将集合转换为列表可以得到预期结果:
>>> mt.isin(element, list(test_set)).execute() array([[ False, True], [ True, False]])