假设我有这些二维数组 A
和 B
。
如何从 A
中删除 B
中的元素。 (集合论中的补码:A-B)
A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]])
B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]])
#output = [[1,1,2], [1,1,3]]
更准确地说,我想做这样的事情。
data = some numpy array
label = some numpy array
A = np.argwhere(label==0) #[[1 1 1], [1 1 2], [1 1 3], [1 1 4]]
B = np.argwhere(data>1.5) #[[0 0 0], [1 0 2], [1 0 3], [1 0 4], [1 1 0], [1 1 1], [1 1 4]]
out = np.argwhere(label==0 and data>1.5) #[[1 1 2], [1 1 3]]
最佳答案
list comprehension 有一个简单的解决方案,
A = [i for i in A if i not in B]
结果
[[1, 1, 2], [1, 1, 3]]
列表推导不会从数组中删除元素,它只是重新分配 - 如果要删除元素,请使用此方法:
for i in B:
if i in A:
A.remove(i)
关于python - 从一个数组中删除另一个数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40055835/