如何使用日期时间索引在 pandas 中进行插值重新索引? [英] How can I do an interpolating reindex in pandas using datetime indices?

查看:100
本文介绍了如何使用日期时间索引在 pandas 中进行插值重新索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有日期时间索引的系列,我想要使用其他任意的日期时间索引对数据进行插值.本质上,我想要的是如何使以下代码段或多或少地起作用:

I have a series with a datetime index, and what I'd like is to interpolate this data using some other, arbitrary datetime index. Essentially what I want is how to make the following code snippet more or less work:

from pandas import Series
import datetime

datetime_index = [datetime.datetime(2010, 1, 5), datetime.datetime(2010, 1, 10)]
data_series = Series([5, 15], [datetime.datetime(2010, 1, 5), datetime.datetime(2010, 1, 15)])

def interpolating_reindex(data_series, datetime_index):
    """?????"""

goal_series = interpolating_reindex(data_series, datetime_index) 

assert(goal_series == Series([5, 10], datetime_index))

reindex不能执行我想要的操作,因为它无法插值,而且我的系列可能也没有相同的索引. resample不是我想要的,因为我想使用一个任意的,已经定义的索引,该索引不一定是周期性的.我还尝试过使用Index.join组合索引,希望以后可以先做reindex然后再做interpolate,但这并没有达到我的预期.有指针吗?

reindex doesn't do what I want because it can't interpolate, and also my series might not have the same indices anyway. resample isn't what I want because I want to use an arbitrary, already defined index which isn't necessarily periodic. I've also tried combining indices using Index.join in the hopes that I could then do reindex and then interpolate, but that didn't work as I expected. Any pointers?

推荐答案

尝试一下:

from pandas import Series
import datetime

datetime_index = [datetime.datetime(2010, 1, 5), datetime.datetime(2010, 1, 10)]
s1 = Series([5, 15], [datetime.datetime(2010, 1, 5), datetime.datetime(2010, 1, 15)])
s2 = Series(None, datetime_index)
s3 = s1.combine_first(s2)
s3.interpolate()

基于注释,插值到目标索引的结果将是:

Based on the comments, the result interpolated to the target index would be:

goal_series  = s3.interpolate().reindex(datetime_index)

assert((goal_series == Series([5, 10], datetime_index)).all())

这篇关于如何使用日期时间索引在 pandas 中进行插值重新索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆