使用numpy.interp进行线性插值

时间:2012-10-31 20:26:22

标签: python numpy interpolation linear-interpolation

我有一个浮点数的一维数组A,其中大部分是好的,但缺少一些值。丢失的数据被替换为nan(不是数字)。我必须通过线性插值从附近的好值中替换数组中的缺失值。所以,例如:

F7(np.array([10.,20.,nan,40.,50.,nan,30.])) 

应该返回

np.array([10.,20.,30.,40.,50.,40.,30.]). 

使用Python做到这一点最好的方法是什么?

非常感谢任何帮助

由于

3 个答案:

答案 0 :(得分:13)

您可以使用scipy.interpolate.interp1d

>>> from scipy.interpolate import interp1d
>>> import numpy as np
>>> x = np.array([10., 20., np.nan, 40., 50., np.nan, 30.])
>>> not_nan = np.logical_not(np.isnan(x))
>>> indices = np.arange(len(x))
>>> interp = interp1d(indices[not_nan], x[not_nan])
>>> interp(indices)
array([ 10.,  20.,  30.,  40.,  50.,  40.,  30.])

编辑:我花了一段时间才弄明白np.interp是如何运作的,但这也可以完成这项工作:

>>> np.interp(indices, indices[not_nan], x[not_nan])
array([ 10.,  20.,  30.,  40.,  50.,  40.,  30.])

答案 1 :(得分:7)

我会选择pandas。使用oneliner的简约方法:

from pandas import *
a=np.array([10.,20.,nan,40.,50.,nan,30.])
Series(a).interpolate()   

Out[219]:
0    10
1    20
2    30
3    40
4    50
5    40
6    30

或者如果你想把它保存为数组:

Series(a).interpolate().values

Out[221]:
array([ 10.,  20.,  30.,  40.,  50.,  40.,  30.])

答案 2 :(得分:0)

要在每次要插值数据时都不创建新的Series对象或Series中的新项目,请使用RedBlackPy。请参见下面的代码示例:

import redblackpy as rb

# we do not include missing data
index = [0,1,3,4,6]
data = [10,20,40,50,30]
# create Series object
series = rb.Series(index=index, values=data, dtype='float32',
                   interpolate='linear')

# Now you have access at any key using linear interpolation
# Interpolation does not creates new items in Series
print(series[2]) # prints 30
print(series[5]) # prints 40
# print Series and see that keys 2 and 5 do not exist in series
print(series)

最后输出如下:

Series object Untitled
0: 10.0
1: 20.0
3: 40.0
4: 50.0
6: 30.0
相关问题