源代码:import pandas as pd
import numpy as np
from statsmodels.tsa.holtwinters import ExponentialSmoothing
data ={'1962 年':[589,561,640,656,727,697,640,599,568,577,553,582],
'1963 年':[600,566,653,673,742,716,660,617,583,587,565,598],
'1964 年':[628,618,688,705,770,736,678,639,604,611,594,634],
'1965 年':[658,622,709,722,782,756,702,653,615,621,602,635],
'1966 年':[677,635,736,755,811,798,735,697,661,667,645,688],
'1967 年':[713,667,762,784,837,817,767,722,681,687,660,698],
'1968 年':[717,696,775,796,858,826,783,740,701,706,677,711],
'1969 年':[734,690,785,805,871,845,801,764,725,723,690,734],
'1970 年':[750,707,807,824,886,859,819,783,740,747,711,751],
'1971 年':[804,756,860,878,942,913,869,834,790,800,763,800],
'1972 年':[826,799,890,900,961,935,894,855,809,810,766,805],
'1973 年':[821,773,883,898,957,924,881,837,784,791,760,802],
'1974 年':[828,778,889,902,969,947,908,867,815,812,773,813],
'1975 年':[834,782,892,903,966,937,896,858,817,827,797,843]}
# 将数据转换为 DataFrame
df = pd.DataFrame(data)
# 拟合每个年份的数据
for column in df.columns:
if not df[column].isnull().any():
data_to_fit = df[column]
print(f"Fitting data for the year: {column}")
print(f"Data to fit:{data_to_fit}") # 打印查看数据
# 使用霍特-温特斯模型提取趋势效应
# 显式地设置 initialization_method 为'estimated',即使不使用 Box-Cox 变换
model = ExponentialSmoothing(data_to_fit.values.reshape(-1, 1),
trend='add',
seasonal='add',
seasonal_periods=12,
use_boxcox=False,
initialization_method='estimated')
try:
model_fit = model.fit() # 不使用 Box-Cox 变换
trend = model_fit.fittedvalues
# 输出趋势效应
print("Fitted values:", trend)
except Exception as e:
print(f"An error occurred: {e}")
else: