How to remove the adjacent duplicate value in a numpy array?

后端 未结 4 2112
萌比男神i
萌比男神i 2020-12-19 06:47

Given a numpy array, I wish to remove the adjacent duplicate non-zero value and all the zero value. For instance, for an array like that: [0,0,1,1,1,2,2,0,1,3,3,3]

4条回答
  •  星月不相逢
    2020-12-19 07:10

    import numpy as np
    a = np.array([0,0,1,1,1,2,2,0,1,3,3,3])
    

    Use integer indexing to choose the non-zero elements

    b = a[a.nonzero()]
    
    >>> b
    array([1, 1, 1, 2, 2, 1, 3, 3, 3])
    >>>
    

    Shift the array to the left and add an element to the end to compare each element with its neighbor. Use zero since you know there aren't any in b.

    b1 = np.append(b[1:], 0)
    
    >>> b1
    array([1, 1, 2, 2, 1, 3, 3, 3, 0])
    >>>
    

    Use boolean indexing to get the values you want.

    c = b[b != b1]
    
    >>> c
    array([1, 2, 1, 3])
    >>> 
    

提交回复
热议问题