我有两个数组,它们的维度相同但长度不同。
Arr1 = np.array([[Ind1],[Ind2],[Ind3]])
Arr2 = np.array([[Ind7],[Ind3],[Ind3],[Ind4]])
我需要获取两个数组中相同位置且相等的元素的位置和值。
在这个例子中,期望的答案将是:
位置 = 2
值 = Ind3
我正在使用带有numpy模块的Python。
我有两个数组,它们的维度相同但长度不同。
Arr1 = np.array([[Ind1],[Ind2],[Ind3]])
Arr2 = np.array([[Ind7],[Ind3],[Ind3],[Ind4]])
我需要获取两个数组中相同位置且相等的元素的位置和值。
在这个例子中,期望的答案将是:
位置 = 2
值 = Ind3
我正在使用带有numpy模块的Python。
使用NumPy数组时,您可能希望以矢量化的方式进行工作,以获得更好的性能并利用数组切片。考虑到这一点,以下是一种针对输入数组a
和b
的方法 -
n = min(len(a), len(b))
out_idx = np.flatnonzero(a[:n] == b[:n])
out_val = a[out_idx] # or b[out_idx] both work
这个可以处理多个匹配项。
示例运行 -
In [224]: a = np.array([3, 8, 9, 2, 1, 7])
In [225]: b = np.array([1, 2, 9, 7, 5, 7, 0, 4])
In [226]: n = min(len(a), len(b))
...: out_idx = np.flatnonzero(a[:n] == b[:n])
...: out_val = a[out_idx]
...:
In [227]: out_idx
Out[227]: array([2, 5])
In [228]: out_val
Out[228]: array([9, 7])
In [229]: zip(out_idx, out_val)
Out[229]: [(2, 9), (5, 7)]
In [230]: {i:j for i,j in zip(out_idx, out_val)}
Out[230]: {2: 9, 5: 7}
lst_1
和lst_2
,您可以这样操作:for i in range(min(len(lst_1), len(lst_2)):
if lst_1[i] == lst_2[i]:
return lst_1[i], i
None
。np.intersect1d(a,b)
当我尝试比较两个不同大小的数组时,我遇到了相同的问题。我只需将它们转换为列表,现在就不会出现任何警告/错误。
我用于将数组转换为列表的代码是 -
import numpy as np
np.array([[1,2,3],[4,5,6]]).tolist()