我有两个数组
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 数组似乎无法使用。有人可以帮我吗?
最佳答案
您可以定义一个数据类型,该数据类型将是您的列的串联,从而允许您使用一维集合运算:
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])
请注意最后一个示例中如何恢复原始数据类型。
关于python - Python 中 ND 数组的“删除”命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726345/