2017-06-22 74 views
0

所以,這讓我有點難住。我有一個字典,我試圖迭代,我正在尋找峯值。這個概念是在這裏:迭代字典,比較當前和以前的值

out = {} 
for i in data.keys(): 
    if(data[i].next() -2 > data[i]: 
     out.update(i, data[i]) 

我試圖把這個在list(range(len(data))),並通過這種方式,與虛擬數據迭代工作。但是我的數據不具有鍵,如1,2,3,4,〔實施例數據:

{ 29600: 0.65867825014992798, 
30000: 1.3958743297851659, 
30400: 2.1166100767879361, 
30800: 2.0297784488567414, 
31200: 1.9480822174184762, 
31600: 1.887373119058025, 
32000: 1.8890589139490572, 
32400: 4.1795916676025842, 
32800: 3.828821494194075, 
33200: 3.7060572197219459, 
33600: 3.647037270729065, 
34000: 3.6029200898094329, 
34400: 3.5352886422138452, 
34800: 6.7902577064444039, 
35200: 6.857, 

裏有數據,點中通過一個較大的值值升高(大約3),我想找到與這些點相關的索引和值。因此,我正在使用下一個值 - 2並查看它是否仍比我的支票大。如果它更容易,這個詞典可以很容易地成爲一個熊貓數據系列。

+0

你能給出你的例子的峯值嗎? – Tbaki

+0

請記住,除非您創建[OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict),否則字典不會被排序。所以像你一樣迭代現在依靠你的「下一個」值是一些數字並不總是會起作用。 – MCBama

+0

我已經添加了更好的示例數據@Tbaki,而這完全不起作用,我無法迭代數據。 –

回答

3

你可以保持按鍵的名單與排序順序,然後用它來遍歷明顯字典:

data = { 29600: 0.65867825014992798, 
     30000: 1.3958743297851659, 
     30400: 2.1166100767879361, 
     30800: 2.0297784488567414, 
     31200: 1.9480822174184762, 
     31600: 1.887373119058025, 
     32000: 1.8890589139490572, 
     32400: 4.1795916676025842, 
     32800: 3.828821494194075, 
     33200: 3.7060572197219459, 
     33600: 3.647037270729065, 
     34000: 3.6029200898094329, 
     34400: 3.5352886422138452, 
     34800: 6.7902577064444039, 
     35200: 6.857} 

out = {} 
# keep the keys in sorted order 
sorted_keys = sorted(data) 

# now for each key in the list 
for i in range(len(sorted_keys)-1): 

    # get key at index i and key at index i+1 and compare them 
    if(data[sorted_keys[i+1]] -2 > data[sorted_keys[i]]): 

     # if condition matched update the out 
     out[sorted_keys[i]] = data[sorted_keys[i]] 
     out[sorted_keys[i+1]] = data[sorted_keys[i+1]] 

print(out) 

輸出:

{32000: 1.8890589139490572, 
32400: 4.179591667602584, 
34400: 3.535288642213845, 
34800: 6.790257706444404} 
+1

太好了,我不知道'sorted()'! –

+0

@NickHale我很高興它的工作! '快樂的編碼'。 – 0p3n5ourcE

2

使用數據幀,因爲你沒事跟大熊貓:

輸入

k  v 
0 29600 0.658678250149928 
1 30000 1.395874329785166 
2 30400 2.116610076787936 
3 30800 2.0297784488567414 
4 31200 1.948082217418476 
5 31600 1.887373119058025 
6 32000 1.8890589139490568 
7 32400 4.179591667602584 
8 32800 3.8288214941940755 
9 33200 3.7060572197219455 
10 33600 3.647037270729065 
11 34000 3.602920089809433 
12 34400 3.5352886422138448 
13 34800 6.790257706444404 
14 35200 6.86 


d["new"] = d.v - d.v.shift(-1) 
d["new"] = d["new"].apply(lambda x:abs(x)) 
d[d["new"] >2] 

輸出

k  v     new 
6 32000 1.8890589139490568 2.2905327536535274 
12 34400 3.5352886422138448 3.254969064230559 
+0

這對我有用,很好的答案,我只能接受一個! –

+0

@NickHale沒問題,祝你好運:D – Tbaki