Find a sequence and remove previous entries

Viewed 49

i have a question regarding the optimization of my code.

Signal = pd.Series([1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0])

I have a pandas series containing periodic bitcode. My aim is remove all entries that start before a certain sequence e.g. 1,1,0,0. So in my example I would expect a reduced series like that:

[1, 1, 0, 0, 1, 1, 0, 0]

I already have a solution for 1, 1 but its not very elegant and not that easily modified for my example: 1,1,0,0.

    i = 0
    bool = True
    while bool:
        a = Signal.iloc[i]
        b = Signal.iloc[i + 1]
        if a == 1 and b == 1:
            bool = False
        else:
            i = i + 1

   Signal = Signal[i:]

I appreciate your help.

2 Answers

We could take a rolling window view of the series with view_as_windows, check for equality with the sequence and find the first occurrence with argmax:

from skimage.util import view_as_windows

seq = [1, 1, 0, 0]
m = (view_as_windows(Signal.values, len(seq))==seq).all(1)
Signal[m.argmax():]

3     1
4     1
5     0
6     0
7     1
8     1
9     0
10    0
dtype: int64

I would go for regex - use a web interface to identify the pattern.

for example:

1,1,0,0,(.*\d)

would result in a group(1) output, that consists of all digits after the 1,1,0,0 pattern.

Related