【发布时间】:2020-03-03 04:10:09
【问题描述】:
我有两个二维数组 a 和 b。我想在b 中找到a 的精确 索引。我遵循了here提出的解决方案。
问题是我的数组包含重复项,您可以在此处看到:
# The shape of b is (50, 2)
b = np.array([[ 0, 1],[ 2, 3],[ 4, 5],[ 6, 7], [ 0, 1],
[10, 11], [12, 13], [14, 15], [16, 17], [10, 11],
[20, 21], [22, 23], [24, 25], [26, 27], [20, 21],
[30, 31], [32, 33], [34, 35], [36, 37], [30, 31],
[40, 41], [42, 43], [44, 45], [46, 47], [40, 41],
[50, 51], [52, 53], [54, 55], [56, 57], [50, 51],
[60, 61], [62, 63], [64, 65], [66, 67], [60, 61],
[70, 71], [72, 73], [74, 75], [76, 77], [70, 71],
[80, 81], [82, 83], [84, 85], [86, 87], [80, 81],
[90, 91], [92, 93], [94, 95], [96, 97], [90, 91]])
# The shape of a is (20,2)
a = np.array([[ 0, 1],[ 2, 3], [ 4, 5],[ 6, 7],[ 0, 1],
[50, 51],[52, 53], [54, 55], [56, 57], [50, 51],
[20, 21], [22, 23], [24, 25], [26, 27], [20, 21],
[70, 71], [72, 73], [74, 75], [76, 77], [70, 71]])
现在当我尝试这样的事情时:
# See the link above approach 2
def view1D(a, b): # a, b are arrays
a = np.ascontiguousarray(a)
b = np.ascontiguousarray(b)
void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
return a.view(void_dt).ravel(), b.view(void_dt).ravel()
def argwhere_nd_searchsorted(a,b):
A,B = view1D(a,b)
sidxB = B.argsort()
mask = np.isin(A,B)
cm = A[mask]
idx0 = np.flatnonzero(mask)
idx1 = sidxB[np.searchsorted(B,cm, sorter=sidxB)]
return idx0, idx1 # idx0 : indices in A, idx1 : indices in B
args0, args1 = argwhere_nd_searchsorted(a,b)
结果:
#args0
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,17, 18, 19])
#args1
array([ 0,
1,
2,
3,
0, # this sould be 4
25,
26,
27,
28,
25, # this sould be 29
10,
11,
12,
13,
10,# this should be 14
39,# this should be 35
36,
37,
38,
39])
# if we check
np.equal(b[args1],a).all() # This returns True
如您所见,args1 突出显示的索引中的问题重复出现。我的预期结果显示在注释行中。
感谢任何帮助
【问题讨论】:
-
有重复。那么,如何进行比赛呢?你将如何决定与哪一个匹配?
-
@Divakar:假设我想更新数组
b如下:b[args1] = another array这将更新重复点的一个实例两次,而其他的保持不变。有些我正在寻找这个问题的解决方案。 -
不要以为你明白我的意思。你在问 -
I want to match rows of array a in b and get a row indices map using numpy.。现在 a 和 b 中都有重复的行。因此,我之前的评论。 -
@Divakar:我更新了这个问题。我的意思是,在代码
args1中不应包含重复的第一个重复点的索引 -
不确定,但您的问题可能会通过掩码解决。所以,你可以使用
isin_nd来获取掩码,它可以用来掩码并赋值给b。