一个用于填充 NaN 值的工具
1 基本用法
DataFrame.interpolate(
method='linear',
*,
axis=0,
limit=None,
inplace=False,
limit_direction=None,
limit_area=None,
downcast=_NoDefault.no_default,
**kwargs)
2 主要参数
method | 多种插值技术
|
axis | 沿着那个轴插值 |
inplace | 是否替换原DataFrame |
limit | 限制连续 NaN 值的数量,即连续的 NaN 值中有多少个可以被插值假设你有一个序列 [1, NaN, NaN, NaN, 5] ,如果你设置 limit=2 ,那么只有前两个 NaN 值会被插值,而第三个会保持为 NaN |
limit_direction: |
|
limit_area |
|
2 举例
2.1 基本用法
import pandas as pd
import numpy as np
s = pd.Series([4,np.nan, np.nan, 3, np.nan, np.nan, 6, np.nan, np.nan,10])
s.interpolate(method='linear')
'''
0 4.000000
1 3.666667
2 3.333333
3 3.000000
4 4.000000
5 5.000000
6 6.000000
7 7.333333
8 8.666667
9 10.000000
dtype: float64
'''
2.2 limit
import pandas as pd
import numpy as np
s = pd.Series([1, np.nan, np.nan, np.nan, 5])
s.interpolate(method='linear', limit=2)
'''
0 1.0
1 2.0
2 3.0
3 NaN
4 5.0
dtype: float64
'''
2.3 limit_direction
import pandas as pd
import numpy as np
s = pd.Series([1, np.nan, np.nan, np.nan, 5])
s.interpolate(method='linear', limit=1, limit_direction='forward')
'''
0 1.0
1 2.0
2 NaN
3 NaN
4 5.0
dtype: float64
'''
s.interpolate(method='linear', limit=1, limit_direction='backward')
'''
0 1.0
1 NaN
2 NaN
3 4.0
4 5.0
dtype: float64
'''
s.interpolate(method='linear', limit_area=None)
'''
0 NaN
1 NaN
2 3.0
3 4.0
4 5.0
5 6.0
6 6.0
7 6.0
dtype: float64
'''