查找两个NumPy数组的并集

  • Post category:Python

想要查找两个NumPy数组的并集,可以使用np.union1d()函数。

该函数的语法如下:

np.union1d(ar1, ar2)

其中,ar1ar2是要进行求并集操作的两个NumPy数组。

下面是两条示例说明:

示例1:

import numpy as np

# 创建两个NumPy数组
a = np.array([1, 2, 3, 4, 5])
b = np.array([4, 5, 6, 7, 8])

# 使用np.union1d()函数求并集
result = np.union1d(a, b)

# 输出结果
print(result)  # [1 2 3 4 5 6 7 8]

在此示例中,首先创建了两个NumPy数组ab,并分别赋值为[1, 2, 3, 4, 5][4, 5, 6, 7, 8]。接着,使用np.union1d()函数对这两个数组进行求并集操作,得到了结果[1 2 3 4 5 6 7 8]

示例2:

import numpy as np

# 创建两个NumPy数组
a = np.array([1, 1, 2, 3, 3, 3, 4, 5])
b = np.array([3, 3, 6, 7, 8])

# 使用np.union1d()函数求并集
result = np.union1d(a, b)

# 输出结果
print(result)  # [1 2 3 4 5 6 7 8]

在此示例中,首先创建了两个NumPy数组ab,并分别赋值为[1, 1, 2, 3, 3, 3, 4, 5][3, 3, 6, 7, 8]。需要注意的是,这两个数组中都包含重复的元素。接着,使用np.union1d()函数对这两个数组进行求并集操作,得到了结果[1 2 3 4 5 6 7 8]。可以发现,np.union1d()函数会自动将重复的元素去重,只保留一个元素进行计算。