10 python interpolation numpy linear-interpolation
我有一个浮点数的一维数组A,其中大部分是好的,但缺少一些值.丢失的数据被替换为nan(不是数字).我必须通过线性插值从附近的好值中替换数组中的缺失值.所以,例如:
F7(np.array([10.,20.,nan,40.,50.,nan,30.]))
Run Code Online (Sandbox Code Playgroud)
应该回来
np.array([10.,20.,30.,40.,50.,40.,30.]).
Run Code Online (Sandbox Code Playgroud)
使用Python做到这一点最好的方法是什么?
任何帮助将非常感激
谢谢
Fre*_*Foo 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.])
Run Code Online (Sandbox Code Playgroud)
编辑:我花了一段时间才弄清楚它是如何np.interp工作的,但这也可以完成这项工作:
>>> np.interp(indices, indices[not_nan], x[not_nan])
array([ 10., 20., 30., 40., 50., 40., 30.])
Run Code Online (Sandbox Code Playgroud)
我会去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
Run Code Online (Sandbox Code Playgroud)
或者,如果您想将其保留为数组:
Series(a).interpolate().values
Out[221]:
array([ 10., 20., 30., 40., 50., 40., 30.])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20931 次 |
| 最近记录: |