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

后端 未结 4 2119
萌比男神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])
    

    first, remove the zeros:

    >>> idx = a==0
    >>> a = a[-idx1]
    >>> a
      array([1, 1, 1, 2, 2, 1, 3, 3, 3])
    

    now remove the consecutive duplicates

    note that ediff1d(a) & a have different shapes, hence a1 is not the result; the leading value of a has to be pre-pended to it, as i did in the last three lines below)

    >>> idx = NP.array(NP.ediff1d(a), dtype=bool)
    >>> a1 = a[1:][idx]
      array([2, 1, 3])
    

    create an empty array to store the result

    >>> a0 = NP.empty(shape=(a1.shape[0]+1,))
    >>> a0[0] = a[0]
    >>> a0[1:] = a1
    >>> a0
      array([ 1, 2, 1, 3])
    

提交回复
热议问题