给定一个元组列表,例如[(x1, y1), (x2, y2) ... (xm, ym)]之类的[(1, 2), (3, 7), (5, 9)]我想编写一个函数,该函数用邻居值f(x-1),f(x + 1)的平均值填充缺失的整数值x。

在这种情况下,我们将获得:

[(1, 2), (2, ave(2, 7)), (3, 7), (4, ave(7, 9)), (5, 9)]

import numpy as np

# calculating nearest neighbor averages
def nearest(x, y):

# define the min and max for our line
min = np.amin(x)
max = np.amax(x)

# fill in the gaps
numsteps = max - min + 1

# an empty vessel
new_df = []

# an empty vessel for our xs
xs = np.linspace(min, max, numsteps)

for i, item in enumerate(xs):
    if(xs[i] in x):
        idx = x.index(xs[i])
        new_df.insert(i, (xs[i], y[idx]))
    else:
        idx = x.index(xs[i] - 1)
        idx2 = x.index(xs[i] + 1)
        avg = (y[idx] + y[idx2])/2.0
        new_df.insert(i, (xs[i], avg))

print new_df


nearest([1, 3, 5], [6, 7, 8])

// [(1.0, 6), (2.0, 6.5), (3.0, 7), (4.0, 7.5), (5.0, 8)]


但是,对于诸如xs = [1, 4, 7]的数组,此操作很快就会失败,因为这些值之间的距离不止一个。在那种情况下,给定相同的ys = [2, 7, 9],我们希望答案是:

[(1, 2), (2, ave(2, 7)), (3, ave(2,7)), (4, 7) ... ]

要么

有点复杂:

[(1, 2), (2, ave(prev, next_that_exists)), (3, ave(just_created, next_that exists), ...]

如何实现,以便我们找到丢失的元素正下方的元素,并找到丢失的元素正上方的元素,并计算其平均值?

此外,这是否与移动平均线不同?

最佳答案

这应该工作:

def nearest(x, y):
    assert len(x) == len(y)

    res = []
    for i in xrange(len(x)-1):
        res.append((x[i], y[i]))
        gap = x[i+1] - x[i]
        for j in xrange(1, gap):
            res.append((x[i]+j, y[i] + j * (y[i+1]-y[i]) / float(gap)))
    res.append((x[-1], y[-1]))

    return res


样本输出:

print nearest([1, 3, 5], [2, 7, 9])
print nearest([1, 4, 7], [2, 7, 9])


给出:

[(1, 2), (2, 4.5), (3, 7), (4, 8.0), (5, 9)]
[(1, 2), (2, 3.666666666666667), (3, 5.333333333333334), (4, 7), (5, 7.666666666666667), (6, 8.333333333333334), (7, 9)]


说明:

我手动解决了[1, 4][2, 7]的情况,并指出我们想要的值是2, x, y, 7

x = (2 + y) / 2
y = (x + 7) / 2


我得到了x = 11/3y = 16/3,产生了:

6/3, 11/3, 16/3, 21/3


请注意,它们之间的间隔为5/3(7-2) / (4-1)。从那时起,我意识到,要通过较大间隙填充相邻值的平均值,您基本上希望在给定的步长上从一个值到下一个值进行线性插值。也就是说,例如,假设您要以2步骤从7转到3,则将5/3重复添加到2直到到达7

关于python - 计算数组中的邻居值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32541427/

10-10 14:25