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

使用AWS Amazon Forecast时遇pd.concat类型错误求助

修复Amazon Forecast可视化代码中的TypeError错误

错误原因

你的代码触发TypeError的核心问题:

  • pd.concat()的作用是合并多个Series或DataFrame对象,但你直接传入了包含datetime对象和单个数值的字典,不符合参数要求。
  • 每次循环都直接用pd.concat的结果覆盖results_df,逻辑上也不是在追加数据,而是每次都替换成新的错误对象。

修复后的代码

import pandas as pd
import dateutil.parser

# 初始化空列表存储所有数据行
data_rows = []

# 处理实际观测数据
for index, row in actuals.iterrows():
    clean_timestamp = dateutil.parser.parse(row['timestamp'])
    data_rows.append({
        'timestamp': clean_timestamp,
        'value': row['target_value'],
        'source': 'actual'
    })

# 处理P10预测数据
for index, row in forecasts_p10_df.iterrows():
    clean_timestamp = dateutil.parser.parse(row['Timestamp'])
    data_rows.append({
        'timestamp': clean_timestamp,
        'value': row['Value'],
        'source': 'p10'
    })

# 处理P50预测数据
for index, row in forecasts_p50_df.iterrows():
    clean_timestamp = dateutil.parser.parse(row['Timestamp'])
    data_rows.append({
        'timestamp': clean_timestamp,
        'value': row['Value'],
        'source': 'p50'
    })

# 处理P90预测数据
for index, row in forecasts_p90_df.iterrows():
    clean_timestamp = dateutil.parser.parse(row['Timestamp'])
    data_rows.append({
        'timestamp': clean_timestamp,
        'value': row['Value'],
        'source': 'p90'
    })

# 一次性生成完整的DataFrame
results_df = pd.DataFrame(data_rows)

# 执行透视并绘图
pivot_df = results_df.pivot(columns='source', values='value', index="timestamp")
pivot_df.plot(figsize=(15, 7))

关键改进点

  1. 先用列表收集所有单条数据的字典,最后一次性生成DataFrame,比循环中反复调用pd.concat效率更高,也符合pandas的最佳实践。
  2. 彻底避免了将单个非Series/DataFrame对象传入pd.concat的错误,确保数据构造逻辑正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 02:20:12