根据Python中最近的数据点已知值确定数组上位置的值

时间:2014-09-23 11:49:39

标签: python arrays

我想知道根据Python中最近的数据点已知值确定数组位置值的有效方法是什么?

问题描述: 数组中有数据点,相距1000个单位,其值已知(见图)。但是,有数据点位于已知数据点之间,其值应根据其最近的已知数据点确定。

例如,在该图之后,位置124200处的数据点的值应设置为 435和位置124850的数据点的值应设置为380。

determining the values of the datapoints in an array

目前,我这样做:

# 'values' is an array which has the values for the known datapoints 
# 'position' is an array that has the datapoints which their values should be determined
# 'step' keeps the number of units in between two datapoints with known values

for pos in positions:
    if pos % step <= 500:
        idx = (( pos - (pos % step)) / step) - 1
        n.append(values[idx])
    else:       #pos % step > 500:
        idx = (( pos + (step - (pos % step))) / step)  - 1
        n.append(values[idx])

我还在考虑使用加法和减法运算来实现逻辑而不是模运算和除法运算但是在与朋友讨论之后我们得出结论:现代处理器在进行除法和乘法时与加法和减法一样快所以我把这个选项排除在外。

提前感谢您的建议。

1 个答案:

答案 0 :(得分:0)

我认为以下代码回答了我的问题:

import numpy as np
indices = np.around(np.array(positions) / step).astype(int)
for idx in indices:
    n.append(values[idx])