0

I have a list for which I need to remove continuously repeating values.

For example: input:

Xin = [1,1,1,1,1,2,2,2,3,2,2,2,2,2,3,3,1]

output:

Yout = [1,2,3,2,3,1]

(Zero is not a legal value in this case).

My current code is this:

Yout = np.zeros(len(Xin))          #initialize a list

for i in range(len(Xin)):          
    if Xin[i] != Xin[i-1]:     
        You[j] = Xin[i]
        j = j + 1

Yout = np.ma.masked_equal(Yout,0) #mask all the zeros
Yout = Yout.compressed()          #Remove all the masks

Someone had answered this for 'R', but I need this for Python.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Malcolm Rest
  • 103
  • 7

1 Answers1

0
import numpy as np

a = np.array([1,1,1,1,1,2,2,2,3,2,2,2,2,2,3,3,1])
print(a)
# [1 1 1 1 1 2 2 2 3 2 2 2 2 2 3 3 1]

b = a[a != np.r_[a[1:], None]]
print(b)
# [1 2 3 2 3 1]
0xF4D3C0D3
  • 747
  • 1
  • 5
  • 15