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

Plotly趋势线使用报错:无法将date列转为数值类型

解决Plotly绘制OLS趋势线时的日期类型报错问题

报错原因

报错信息明确说明:

ValueError: Could not convert value of 'x' ('date') into a numeric type.
If 'x' contains stringified dates, please convert to a datetime column.

问题出在Plotly的OLS趋势线计算要求x轴为数值类型,但你的date列目前是字符串格式,无法直接用于OLS回归运算。

解决步骤

  1. 转换日期列类型
    用Pandas的pd.to_datetime()函数把字符串格式的日期转为datetime类型,代码示例:

    import pandas as pd
    # 提取目标DataFrame
    df = companies_dates["AAPL"]
    # 将date列转换为datetime类型
    df["date"] = pd.to_datetime(df["date"])
    

    如果你的日期格式有特殊规则,可以指定format参数确保转换准确,比如:

    df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
    
  2. 重新执行绘图代码
    日期列类型转换完成后,再运行你的绘图代码就能正常生成带OLS趋势线的曲线:

    import plotly.express as px
    fig = px.scatter(df, x="date", y=["SMA_fast", "SMA_slow"], trendline="ols")
    fig.update_traces(mode = "lines")
    fig.show()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:45:38