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

后端 未结 4 2108
萌比男神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:08

    Here's one way:

    In [62]: x
    Out[62]: array([0, 0, 1, 1, 1, 2, 2, 0, 1, 3, 3, 3])
    
    In [63]: selection = np.ones(len(x), dtype=bool)
    
    In [64]: selection[1:] = x[1:] != x[:-1]
    
    In [65]: selection &= x != 0
    
    In [66]: x[selection]
    Out[66]: array([1, 2, 1, 3])
    

提交回复
热议问题