时间序列趋势分解 seasonal_decompose

文章目录

  • 生成数据:
  • 乘法序列分解
  • 加法序列分解

乘法序列 = Trend * Seasonality * Error

生成数据:

import numpy as np
import pandas as pd
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randint(1, 10, size=(365, 1)), columns=['value'],index=pd.date_range('2021-01-01', periods=365, freq='D'))  

乘法序列分解

乘法序列 = Trend * Seasonality * Error

result_mul = seasonal_decompose(df['value'], model='multiplicative', extrapolate_trend='freq')

plt.rcParams.update({'figure.figsize': (10, 10)})
result_mul.plot().suptitle('Multiplicative Decompose')
plt.show()

加法序列分解

加法序列 = Trend + Seasonality + Error

result_add = seasonal_decompose(df['value'], model='additive', extrapolate_trend='freq')
plt.rcParams.update({'figure.figsize': (10, 10)})
result_add.plot().suptitle('Additive Decompose')
plt.show()

如果有ValueError: You must specify a period or x must be a pandas object with a DatetimeIndex with a freq not set to None报错,可以设置period参数,比如:

seasonal_decompose(price_df['price'], model='additive', extrapolate_trend='freq', period=3)

你可能感兴趣的:(数据处理,python)