Removing elements from an array that are in another array

后端 未结 5 920
抹茶落季
抹茶落季 2020-11-30 04:06

Say I have these 2D arrays A and B.

How can I remove elements from A that are in B. (Complement in set theory: A-B)

A=np.asarray([[1,1,1], [1,1,2], [         


        
5条回答
  •  猫巷女王i
    2020-11-30 04:43

    If you want to do it the numpy way,

    import numpy as np
    
    A = np.array([[1, 1, 1,], [1, 1, 2], [1, 1, 3], [1, 1, 4]])
    B = np.array([[0, 0, 0], [1, 0, 2], [1, 0, 3], [1, 0, 4], [1, 1, 0], [1, 1, 1], [1, 1, 4]])
    A_rows = A.view([('', A.dtype)] * A.shape[1])
    B_rows = B.view([('', B.dtype)] * B.shape[1])
    
    diff_array = np.setdiff1d(A_rows, B_rows).view(A.dtype).reshape(-1, A.shape[1])
    

    As @Rahul suggested, for a non numpy easy solution,

    diff_array = [i for i in A if i not in B]
    

提交回复
热议问题