You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行时间序列seasonal_decompose时因Dataframe含字符串报错如何解决

报错原因

seasonal_decompose 函数仅支持输入数值型的时间序列做运算,你当前传入的df1["Category: All categories"]是存储分类名称的字符串列,无法转换为浮点型参与计算,因此触发该报错。

处理步骤
  • 首先修正数据框的时间索引结构:时间序列分析需要先将时间列转换为 datetime 格式并设置为索引,同时指定固定的观测频率:
import pandas as pd
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pyplot as plt

# 转换时间列格式,设置为索引并指定频率,示例为月度数据,频率可根据实际情况调整
df1['Month'] = pd.to_datetime(df1['Month'])
df1 = df1.set_index('Month').asfreq('MS')
  • 选择对应分类的数值列作为分解输入:你需要分解哪个分类的时序趋势,就传入该分类对应的数值列即可,示例为分解chocolate: (United States)分类的时序数据:
# 执行乘法季节性分解
decomposeM = seasonal_decompose(
    df1["chocolate: (United States)"], 
    model='multiplicative', 
    extrapolate_trend='freq'
)

# 绘制分解图
plt.rcParams['figure.figsize'] = (12, 8)
decomposeM.plot().suptitle('Multiplicative Decomposition', fontsize=16)
plt.show()

如果需要批量处理全部分类的分解任务,遍历所有分类数值列循环执行上述逻辑即可。

内容的提问来源于stack exchange,提问作者user17059762

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:57:00