Comparing two numpy arrays and removing elements

前端 未结 3 1849
日久生厌
日久生厌 2020-12-22 04:08

I have been going through several solutions, but I am not able to find a solution I need.

I have two numpy arrays. Let\'s take a small example<

相关标签:
3条回答
  • 2020-12-22 04:50

    If you really do have numpy arrays then you can use numpy.setdiff1d as below

    import numpy as np
    
    x = np.array([1,2,3,4,5,6,7,8,9])
    y = np.array([3,4,5])
    
    z = np.setdiff1d(x, y)
    # array([1, 2, 6, 7, 8, 9])
    
    0 讨论(0)
  • 2020-12-22 05:02

    You can use built-in sets:

    final_x = set(x) - set(y)
    

    and subtract the second from the first. You can convert final_x to a list or numpy.array if you feel so inclined.

    0 讨论(0)
  • 2020-12-22 05:13

    Simply pass the negated version of boolean array returned by np.in1d to array x:

    >>> x = np.array([1,2,3,4,5,6,7,8,9])
    >>> y = [3,4,5]
    >>> x[~np.in1d(x, y)]
    array([1, 2, 6, 7, 8, 9])
    
    0 讨论(0)
提交回复
热议问题