Detecting events in pandas data frame

I have a pandas dataframe consisting of 0.1, -1.

import pandas as pd df=pd.DataFrame({'indicator':[0, 0, 0, -1,0,0,1,0,-1,1,0,-1,0,1]}) 

and I will not look for indices for each -1 and 1, so -1 is followed by some or not one zero and +1. For the example in the above example, I want to get

 [(3,6),(8,9),(11,13)] 
+6
source share
1 answer
 s = pd.DataFrame({'indicator':[0, 0, 0, -1, 0, 0, 1, 0, -1, 1, 0, -1, 0, 1]}).squeeze() # reduce it to non-zeros s1 = s[s!=0] # must be -1 and next one be 1, grab index idx = s1.loc[(s1 == -1) & (s1 != s1.shift(-1))].index # grab s1 index and next index s2 = s1.index.to_series().shift(-1).loc[idx].astype(int) # zip to get tuples zip(s2.index, s2.values) [(3, 6), (8, 9), (11, 13)] 
+5
source

All Articles