python - Finding the last values before a specific value in numpy/pandas -


I have a panda series, and I want to find the last index / status (or boolean mask) Appears before other specific values.

Example given:

  df = pd.DataFrame ({'x': np.random.randint (10, 1000000)})  

I have to find all the locations of 0 which are the last to be 9 before. If my array [9, 0, 3, 0, 1, 9, 4, 9, 0, 0, 9, 4, 0]

in position 3 and 9 only void for me Interested to note that in this I am not worried that what happened with the last 0 in position 12. I do not like to keep it in the set set, but this is not important.

My current method is:

df ['last'] = np.nan df.loc [df.x == 0, 'last'] = 0.0 Df.loc [df.x == 9, 'final'] = 1.0 df.last.fillna (method = 'bfill', inplace = true) df.loc [df.x == 0, 'last'] = np .nan df.last.fillna (method = 'bfill Df.loc [df.x! = 0,' last '] = 0.0

Is there any way a faster or more Is abbreviated?

Optimization, very easily, answers to the AJCR: / P>

  S = pd.Series ([9, 0, 3, 0, 1, 9, 4, 9, 0, 0, 9, 4, 0]) # s [s.isin ([0,9])] [(S == 0) & amp; (S. Shift (-1) == 9)]  

Comments

Popular posts from this blog

HTML/CSS - Automatically set height width from background image? -

php - Mysql Show Process - Sleep Commands and what to do -

c - What is the address of buf (the local variable in the main function)? -