Python Pandas – 用线性插值填补NaN

Python Pandas – 用线性插值填补NaN

要使用线性插值将NaN填补,请在Pandas序列上使用 interpolate() 方法。首先,导入所需的库 −

import pandas as pd
import numpy as np

创建一个带有一些NaN值的Pandas序列。我们使用numpy设置了NaN np.nan

d = pd.Series([10, 20, np.nan, 40, 50, np.nan, 70, np.nan, 90, 100])

找到线性插值 −

d.interpolate()

示例

以下是代码 −

import pandas as pd
import numpy as np

# pandas序列
d = pd.Series([10, 20, np.nan, 40, 50, np.nan, 70, np.nan, 90, 100])

print"序列...\n",d

# 插值
print"\n线性插值...\n",d.interpolate()

输出

这将生成以下输出 −

序列...
0   10.0
1   20.0
2    NaN
3   40.0
4   50.0
5    NaN
6   70.0
7    NaN
8   90.0
9  100.0
dtype: float64

线性插值...
0   10.0
1   20.0
2   30.0
3   40.0
4   50.0
5   60.0
6   70.0
7   80.0
8   90.0
9  100.0
dtype: float64

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程