目的
在时序分析时,我们经常需要将原始序列进行差分,然后做出拟合或者预测,最后还需要将拟合的或者预测的值恢复成原始序列。这里,使用Pandas的Series中的diff和cumsum函数可以方便的实现。
一次一阶差分的恢复
import pandas as pd
time_series = pd.Series([2,4,3,5,6,7,4,5,6,3,2,4], index=pd.date_range(start='2000', periods=12, freq='a'))
time_series_diff = time_series.diff(1).dropna()
time_series_restored = pd.Series([time_series[0]], index=[time_series.index[0]]) .append(time_series_diff).cumsum()
time_series_restored
多次一阶差分的恢复
time_series = pd.Series([2,4,3,5,6,7,4,5,6,3,2,4], index=pd.date_range(start='2000', periods=12, freq='a'))
time_series_diff = time_series
diff_times = 3
first_values = []
for i in range(1, diff_times+1):
first_values.append(pd.Series([time_series_diff[0]],index=[time_series_diff.index[0]]))
time_series_diff = time_series_diff.diff(1).dropna()
time_series_restored = time_series_diff
for first in reversed(first_values):
time_series_restored = first.append(time_series_restored).cumsum()
time_series_restored
原理
其实就是使用cumsum累计求和函数。保留每次一阶差分前的第一个值,然后反序再加回来。
时序问题中,如果预测的是一阶的增量,那么就需要恢复原始的序列。
网友评论