【发布时间】:2021-10-25 16:51:17
【问题描述】:
我正在使用不同的方法探索pandas.DataFrame.interpolate(),linear 与 nearest,当尾随缺少数据时,我发现这两种方法的输出不同。
例如:
import pandas as pd # version: '0.16.2' or '0.20.3'
>>> a = pd.DataFrame({'col1': [np.nan, 1, np.nan, 3, np.nan, 5, np.nan]})
Out[1]:
col1
0 NaN
1 1.0
2 NaN
3 3.0
4 NaN
5 5.0
6 NaN
>>> a.interpolate(method='linear')
Out[2]:
col1
0 NaN
1 1.0
2 2.0
3 3.0
4 4.0
5 5.0
6 5.0
>>> a.interpolate(method='nearest')
Out[3]:
col1
0 NaN
1 1.0
2 1.0
3 3.0
4 3.0
5 5.0
6 NaN
似乎linear 方法会对尾随的 NaN 进行外推,而“最近”方法则不会,除非您指定 fill_value = 'extrapolate':
>>> a.interpolate(method='nearest', fill_value='extrapolate')
Out[4]:
col1
0 NaN
1 1.0
2 1.0
3 3.0
4 3.0
5 5.0
6 5.0
所以我的问题是为什么这两种方法在处理尾随 NaN 时表现不同?这是它应该是什么还是一个错误?
在“0.16.2”和“0.20.3”这两个版本的 pandas 中发现了相同的结果。
pandas.Series.interpolate() 也出现了同样的问题。
有一个thread 和一个github issue 在谈论类似的问题,但目的不同。我正在寻找这个问题的解释或结论。
编辑:
更正:linear 方法的行为方式与extrapolation 不完全相同,您可以看到最后一行的填充值是 5 而不是 6。现在看起来更像是一个错误,是吗?
【问题讨论】:
标签: python pandas interpolation