查找两个 NumPy 数组之间的共同值
在本文中,我们将讨论如何找出两个数组之间的共同值。要找到共同值,我们可以使用 numpy.intersect1d(),它将执行交集运算并按排序顺序返回 2 个数组之间的共同值。
Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False)
Parameters :
arr1, arr2 : [array_like] Input arrays.
assume_unique : [bool] If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
return_indices : [bool] If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False.
Return : [ndarray] Sorted 1D array of common and unique elements.
示例 #1:查找 1d 数组之间的共同值
Python3
import numpy as np
# create 2 arrays
a = np.array([2, 4, 7, 1, 4])
b = np.array([7, 2, 9, 0, 5])
# Display the arrays
print("Original arrays", a, ' ', b)
# use the np.intersect1d method
c = np.intersect1d(a, b)
# Display result
print("Common values", c)
Python3
import numpy as np
# create 2 arrays
a = np.array([2,4,7,1,4,9]).reshape(3,2)
b = np.array([7,2,9,0,5,3]).reshape(2,3)
# Display the arrays
print("Original arrays")
print(a)
print(b)
# use the np.intersect1d method
c = np.intersect1d(a,b)
# Display result
print("Common values",c)
输出:
Original arrays [2 4 7 1 4] [7 2 9 0 5]
Common values [2 7]
示例 #2:查找 n 维数组之间的共同值
Python3
import numpy as np
# create 2 arrays
a = np.array([2,4,7,1,4,9]).reshape(3,2)
b = np.array([7,2,9,0,5,3]).reshape(2,3)
# Display the arrays
print("Original arrays")
print(a)
print(b)
# use the np.intersect1d method
c = np.intersect1d(a,b)
# Display result
print("Common values",c)
输出:
Original arrays
[[2 4]
[7 1]
[4 9]]
[[7 2 9]
[0 5 3]]
Common values [2 7 9]
注意:无论传入什么维度的数组,都会以一维展平的方式返回常用的值