numpy.intersect1d 函数用于返回两个数组的交集。它会返回一个已排序的数组,其中包含在两个输入数组中都存在的唯一元素。返回交集的数组。如果 return_indices=True,返回一个包含交集元素及其在 ar1 和 ar2 中的索引位置的元组。本文主要介绍一下NumPy中intersect1d方法的使用。

numpy.intersect1d

numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)       [source]

找到两个数组的交集。

返回两个输入数组中已排序的唯一值。

参数 :

ar1, ar2 :array_like

输入数组。 如果尚未为1D,则将被展平。

assume_uniquebool

如果为True,则假定输入数组都是唯一的,

这可以加快计算速度。 默认值为False

return_indicesbool

如果为True,则返回与两个数组的交集相对应的索引。

 如果有多个值,则使用值的第一个实例。 默认值为False

 1.15.0版中的新功能。

返回值 :

intersect1dndarray

常见和唯一元素的排序一维数组。

comm1ndarray

ar1中共同值的首次出现的索引。

 仅在return_indices为True时提供。

comm2 :ndarray

ar2中公共值首次出现的索引。

 仅在return_indices为True时提供。

例子

1)基本用法 (返回交集元素)

import numpy as np

array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([3, 5, 6, 7, 8])

intersection = np.intersect1d(array1, array2)
print(f"数组 1: {array1}")
print(f"数组 2: {array2}")
print(f"交集元素: {intersection}")

2)输入包含重复元素 (默认 assume_unique=False)

import numpy as np

array3 = np.array([1, 2, 2, 3, 4, 4, 5])
array4 = np.array([3, 3, 5, 6, 7, 7, 8])

intersection_with_duplicates = np.intersect1d(array3, array4)
print(f"数组 3: {array3}")
print(f"数组 4: {array4}")
print(f"交集元素 (包含重复): {intersection_with_duplicates}")

3)使用 assume_unique=True (假设输入元素唯一)

import numpy as np

array5 = np.array([1, 2, 3, 4, 5])
array6 = np.array([3, 5, 6, 7, 8])

intersection_unique = np.intersect1d(array5, array6, assume_unique=True)
print(f"数组 5: {array5}")
print(f"数组 6: {array6}")
print(f"交集元素 (假设唯一): {intersection_unique}")

4)返回索引 (return_indices=True)

import numpy as np

array7 = np.array([10, 20, 30, 40, 50])
array8 = np.array([30, 50, 60])

intersection_with_indices, indices_a,
indices_b = np.intersect1d(array7,
array8, return_indices=True)
print(f"数组 7: {array7}")
print(f"数组 8: {array8}")
print(f"交集元素: {intersection_with_indices}")
print(f"交集元素在数组 7 中的索引: {indices_a}")
print(f"交集元素在数组 8 中的索引: {indices_b}")

推荐文档

相关文档

大家感兴趣的内容

随机列表