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)]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With