2017-06-22 71 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