1

我有两个数组

A=np.array([[2,0],
            [3,4],
            [5,6]])

B=np.array([[4,3],
            [6,7],
            [3,4],
            [2,0]])

我想从 A 中减去 B 并获得 A 中存在于 B 中的元素的索引。我该如何做到这一点?在这个例子中,我需要这样的答案:

C=[0,1] //index in A of elements repeated in B 
D=[[2,0], [3,4]] //their value 
E=[3,2] //index location of these in B

几个常用的命令,如非零、删除、过滤器等,似乎无法用于 ND 阵列。有人可以帮我吗?

4

1 回答 1

2

您可以定义一个将列连接的数据类型,允许您使用一维集合操作:

a = np.ascontiguousarray(A).view(np.dtype((np.void, A.shape[1]*min(A.strides))))
b = np.ascontiguousarray(B).view(np.dtype((np.void, B.shape[1]*min(B.strides))))

check = np.in1d(a, b)
C = np.where(check)[0]
D = A[check]

check = np.in1d(b, a)
E = np.where(check)[0]

D例如,如果您只想要,您可以这样做:

D = np.intersect1d(a, b).view(A.dtype).reshape(-1, A.shape[1])

请注意在最后一个示例中如何恢复原始 dtype。

于 2014-09-08T14:26:32.190 回答