2017-09-01 65 views
1

最匹配的数字我有一个dataseries:查找数据帧中使用熊猫/ Python的

df = pd.DataFrame({'Values': [-0.8765, -1, -1.2, 3, 4, 5, -12.0021, 10, 11, 12, -0.982]}, 
       index = [pd.Timestamp('20130101 09:00:00'), 
         pd.Timestamp('20130101 09:00:02'), 
         pd.Timestamp('20130101 09:00:03'), 
         pd.Timestamp('20130101 09:00:05'), 
         pd.Timestamp('20130101 09:00:06'), 
         pd.Timestamp('20130101 09:00:07'), 
         pd.Timestamp('20130101 09:00:08'), 
         pd.Timestamp('20130101 09:00:09'), 
         pd.Timestamp('20130101 09:00:10'), 
         pd.Timestamp('20130101 09:00:11'), 
         pd.Timestamp('20130101 09:00:12') 
         ]) 

所以,我必须找到一个模式变成我的数据帧。 例如,我有这样的模式:

pattern = [4,5,-12.0021,10] 

所以,现在我运行这个算法:

print(df.iloc[[int(df.index.get_indexer_for((df[df.Values==i].index))) for i in pattern]]) 

,并返回给我:

     Values 
2013-01-01 09:00:06 4.0000 
2013-01-01 09:00:07 5.0000 
2013-01-01 09:00:08 -12.0021 
2013-01-01 09:00:09 10.0000 

好,冬暖夏凉。

但我还需要在我的数据框中找到SIMILAR模式。

所以,我有以下模式: 图案= [4,5,-12.0021,10] 并且例如,如果我有这个值到我的数据帧:[4,5,-12.01,10.1] 。该算法不返回我,因为它只返回等于,但我也需要返回类似的。

我有什么用?

+0

是一个选项DTW? – brunoelyg

回答

1

this question的一个很好的解决方案建议在numpy阵列上使用广播。

pattern = [4, 5, -12.01, 10.1] 
thresh = 0.1 

out = df[(np.abs(df.Values.values[:, None] - pattern) <= thresh).any(1)] 
out 
         Values 
2013-01-01 09:00:06 4.0000 
2013-01-01 09:00:07 5.0000 
2013-01-01 09:00:08 -12.0021 
2013-01-01 09:00:09 10.0000 

过滤是基于您可以调整的手动应用阈值完成的。