Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting events in a pandas data frame

Tags:

python

pandas

I have a pandas dataframe consisting of 0,1,-1's.

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

and I wan't to find the indices of every -1 and 1 such that the -1 is followed by some or none zeros and a +1. For exapmle in the above example I want to get

[(3,6),(8,9),(11,13)]
like image 301
user128751 Avatar asked Jul 20 '16 08:07

user128751


1 Answers

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)]
like image 199
piRSquared Avatar answered Oct 23 '22 05:10

piRSquared