10

I have a 1 dimensional array A of floats that is mostly good but a few of the values are missing. Missing data is replace with nan(not a number). I have to replace the missing values in the array by linear interpolation from the nearby good values. So, for example:

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

should return

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

What's the best of way of doing this using Python?

Any help would be much appreciated

Thanks

4

3 回答 3

14

你可以使用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.])
于 2012-10-31T20:34:01.800 回答
8

我会去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.])
于 2012-10-31T20:39:56.347 回答
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
于 2018-08-24T20:22:15.533 回答