简体   繁体   English

根据它们在另一个二维数组中的存在从二维数组中删除子数组(返回一个新的二维数组)

[英]Remove subarray from a 2d array based on their existence in another 2d array (return a new 2d array)

I have two 2d array, A and B, like the following.我有两个二维数组,A 和 B,如下所示。

A=array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4],
       [5, 5, 5],
       [6, 6, 6],
       [7, 7, 7],
       [8, 8, 8],
       [9, 9, 9]])
B=array([[1, 1, 1],
       [3, 3, 3],
       [8, 8, 8]])

I want to remove subarrays of A if they exist in B. Then return a new 2d array C like the following:如果 A 的子数组存在于 B 中,我想删除它们。然后返回一个新的二维数组 C,如下所示:

C=array([[2, 2, 2],
       [4, 4, 4],
       [5, 5, 5],
       [6, 6, 6],
       [7, 7, 7],
       [9, 9, 9]])

Currently I have tried the np.isin function but the result is no longer a 2d array.目前我已经尝试过 np.isin 函数,但结果不再是二维数组。

mask = np.isin(A, B, invert=True)
A[mask]
>>array([2, 2, 2, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 9, 9, 9])

You need to aggregate the booleans on axis 1:您需要聚合轴 1 上的布尔值:

C = A[~np.isin(A,B).all(1)]

output:输出:

array([[2, 2, 2],
       [4, 4, 4],
       [5, 5, 5],
       [6, 6, 6],
       [7, 7, 7],
       [9, 9, 9]])

Or in1d :in1d

C = A[~np.in1d(A, B).all(axis=1)]

And now:现在:

print(C)

Output:输出:

[[2 2 2]
 [4 4 4]
 [5 5 5]
 [6 6 6]
 [7 7 7]
 [9 9 9]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM