python - Pandas 插值 'time' 与 'linear'

标签 python pandas dataframe interpolation

Pandas interpolate function , 是 method='time'相当于 method='linear'当时间索引等距时?

一个基本的例子表明情况就是这样:

even_index = pd.date_range('2019-02-20 10:00 am', 
                           '2019-02-20 2:00 pm', freq='1 h')
values = [10, np.nan, 30, np.nan, 50]

pd.DataFrame(values, index=even_index).interpolate(method='time')

                        0
2019-02-20 10:00:00  10.0
2019-02-20 11:00:00  20.0
2019-02-20 12:00:00  30.0
2019-02-20 13:00:00  40.0
2019-02-20 14:00:00  50.0


pd.DataFrame(values, index=even_index).interpolate(method='linear')

                        0
2019-02-20 10:00:00  10.0
2019-02-20 11:00:00  20.0
2019-02-20 12:00:00  30.0
2019-02-20 13:00:00  40.0
2019-02-20 14:00:00  50.0

'time' 和 'linear' 之间的差异似乎只有在时间索引不等距时才会出现:

uneven_index = pd.to_datetime(['2019-02-20 10:00 am', 
               '2019-02-20 10:30 am', '2019-02-20 12:30 pm', 
               '2019-02-20 1:30 pm', '2019-02-20 2:00 pm'])


pd.DataFrame(values, index=uneven_index).interpolate(method='time')

                             0
2019-02-20 10:00:00  10.000000
2019-02-20 10:30:00  14.000000
2019-02-20 12:30:00  30.000000
2019-02-20 13:30:00  43.333333
2019-02-20 14:00:00  50.000000

pd.DataFrame(values, index=uneven_index).interpolate(method='linear')

                        0
2019-02-20 10:00:00  10.0
2019-02-20 10:30:00  20.0
2019-02-20 12:30:00  30.0
2019-02-20 13:30:00  40.0
2019-02-20 14:00:00  50.0

我的问题是这是否总是成立。是否可以假设具有等距时间索引,method='time'将始终执行线性插值?

最佳答案

是的

从文档:

‘linear’: Ignore the index and treat the values as equally spaced



因此,如果您的索引是等距的并且您使用了正确的方法(在您的示例中时间索引的“时间”方法,但它也可能是具有等距值的数字索引的“索引”方法),您确实会得到相同的结果。

关于python - Pandas 插值 'time' 与 'linear',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54985896/

相关文章:

python - 在 lambda 函数中使用条件

python - 根据某些列条件从 Pandas 数据框中获取所有行组合?

pandas - matplotlib:每个类别的箱线图

r - 用数据框合并填充 NA

python - 计算数据框中一行的百分比值

python - 如何在 Python f 字符串中跳过十进制的尾随零?

Python round() 太慢,更快的方法来降低精度?

Python。为类实例启用日志记录,从单独的模块导入

python - 算命先生列表和 raw_input

python-3.x - 有没有办法在 KivyMD 中显示 pandas Dataframe?