迭代dict,比较当前值和之前的值

时间:2017-06-22 15:03:13

标签: python pandas numpy dictionary

所以,这让我有点难过。我有一个dict,我试图迭代,我正在寻找峰值。这个概念在这里:

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.5199005963210857,

数据中有一些点,其中值增加一个大值(大约3),我试图找到索引和与这些点相关的值。因此,我正在使用下一个值 - 2并查看它是否仍然比我的检查更大。如果它更容易,那么这个dict很容易成为熊猫数据系列。

2 个答案:

答案 0 :(得分:3)

您可以按顺序保留键列表,然后使用它来迭代字典:

.gz

输出:

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.5199005963210857}

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)

答案 1 :(得分:2)

使用数据帧,因为你对pandas没问题:

输入

    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.519900596321086


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