Bobe Kryant Bobe Kryant - 3 months ago 6
Python Question

How to remove first occurrence in string repeatedly python?

I am not sure how to continously change the first occurance in a list. For instance, I will have a list of numbers

import numpy as np
test=np.array([np.nan,np.nan,1,1,1,np.nan,1,1])


Which gives me an output of

array([ nan, nan, 1., 1., 1., nan, 1., 1.])


I want to use a function to change this to

array([ nan, nan, nan, 1., 1., nan, nan, 1.])


which removes the first instance of 1 each time it starts.

Answer

You could do something like this -

idx = np.diff(np.append(False,(test==1)).astype(int))==1
test[idx] = np.nan

Sample runs

1) Sample case from posted question -

In [80]: test
Out[80]: array([ nan,  nan,   1.,   1.,   1.,  nan,   1.,   1.])

In [81]: test[np.diff(np.append(False,(test==1)).astype(int))==1] = np.nan

In [82]: test
Out[82]: array([ nan,  nan,  nan,   1.,   1.,  nan,  nan,   1.])

2) Special case with a 1 at the start -

In [72]: test
Out[72]: array([ 1.,  1.,  0.,  1.,  0.,  0.,  1.,  1.,  0.,  1.])

In [73]: test[np.diff(np.append(False,(test==1)).astype(int))==1] = np.nan

In [74]: test
Out[74]: array([ nan,   1.,   0.,  nan,   0.,   0.,  nan,   1.,   0.,  nan])
Comments