检测pandas数据框中的事件

时间:2016-07-20 08:46:56

标签: python pandas

我有一个由0,1,-1和#39组成的pandas数据帧。

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

并且我找不到每个-1和1的索引,这样-1后跟一些或没有零和一个+1。对于上面例子中的exapmle,我想得到

[(3,6),(8,9),(11,13)]

1 个答案:

答案 0 :(得分:5)

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)]