2017-09-01 17 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 

過濾是基於您可以調整的手動應用閾值完成的。