Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用插值法减去两个时间戳不规则和规则的序列_Python_Pandas_Time Series - Fatal编程技术网

Python 用插值法减去两个时间戳不规则和规则的序列

Python 用插值法减去两个时间戳不规则和规则的序列,python,pandas,time-series,Python,Pandas,Time Series,我正在使用时间戳作为索引的两个熊猫系列。一个系列是固定频率的粗模型,另一个系列是无固定频率的数据。我想从数据中减去模型,然后(线性或样条曲线)插值模型的值 以下是一个例子: import numpy as np import pandas as pd # generate model with fixed freq model = pd.Series(range(5),index=pd.date_range('2017-06-19T12:05:00', '2017-06-19T12:25:0

我正在使用时间戳作为索引的两个熊猫系列。一个系列是固定频率的粗模型,另一个系列是无固定频率的数据。我想从数据中减去模型,然后(线性或样条曲线)插值模型的值

以下是一个例子:

import numpy as np
import pandas as pd


# generate model with fixed freq
model = pd.Series(range(5),index=pd.date_range('2017-06-19T12:05:00', '2017-06-19T12:25:00', freq="5 min"))

# generate data and add more_data to make frequency irregular
data = pd.Series(np.arange(10)+0.3,index=pd.date_range('2017-06-19T12:06:00', 
'2017-06-19T12:24:00', freq="2 min"))
more_data = pd.Series([-10, -20], index=[pd.Timestamp('2017-06-19T12:07:35'), 
pd.Timestamp('2017-06-19T12:09:10')])
data = data.append(more_data).sort_index()
我试过了

data - model.interpolate()[data.index]
但这只会在模型和数据的时间戳重叠的地方给出非NaN值

我知道我可以对数据进行重新采样以适应模型的频率(),但我确实希望数据减去数据原始时间戳处的模型。

想法:

您可以在
数据
索引中以纳秒为单位找到值的gcd,然后对模型进行重新采样以适合数据的频率

方法:

使用找到的方法为numpy数组构造gcd函数,并将其馈送到
data.index.astype(np.int64)

然后重新采样
模型
,并按照之前的步骤进行:

data - model.resample(str(divisor)+'ns').interpolate(method='time')[data.index]
    Out[61]: 
2017-06-19 12:06:00     0.100000
2017-06-19 12:07:35   -10.516667
2017-06-19 12:08:00     0.700000
2017-06-19 12:09:10   -20.833333
2017-06-19 12:10:00     1.300000
2017-06-19 12:12:00     1.900000
2017-06-19 12:14:00     2.500000
2017-06-19 12:16:00     3.100000
2017-06-19 12:18:00     3.700000
2017-06-19 12:20:00     4.300000
2017-06-19 12:22:00     4.900000
2017-06-19 12:24:00     5.500000
dtype: float64
因此,在答案的帮助下,我找到了问题的解决方案,只在实际需要的点上插值:

首先,生成一系列时间戳为
data
的NAN:

na = pd.Series(None, data.index)
并将其与模型相结合:

combi = model.combine_first(na)
现在可以从数据中对该序列进行插值和减法

(data - combi.interpolate(method='time'))[data.index]
还是作为一个班轮

(data - model.combine_first(pd.Series(None, data.index)).interpolate(method='time'))[data.index]

这适用于我当前的数据集,尽管重采样非常缓慢。我还遇到了一个更大数据集的内存错误。在这个系列的片段上进行迭代虽然不是很优雅,但应该是可行的。我非常喜欢这个。我唯一要添加的东西是,在我的和这里,我可能要编辑的东西是添加
method='time'
作为
interpolate
的参数,这样插值实际上使用了我们非常小心保存的这些日期时间索引。进一步研究,实际上,只要使用了默认的
method='linear'
之外的任何选项,这两种方法都能正常工作。
(data - model.combine_first(pd.Series(None, data.index)).interpolate(method='time'))[data.index]