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

将Pandas DataFrame写入PostgreSQL时遇InvalidTextRepresentation错误的解决

问题描述

我有一个简单的DataFrame gg,数据如下:

id commodity prediction_date  price_on_prediction_date  
0   2  cc_wheat      2023-04-02                     265.0   

   predicted_time_range  predicted_price predicted_date  occurred_price  
0                    28       219.015029     2023-04-30          237.25   

  date_of_occured_price trend_prediction trend_real result feature_id  
0            2023-04-30                ⬇          ⬇    NaN  554701139  

我需要通过基于psycopg2的自定义类pig的fast_write方法将其写入PostgreSQL数据库,执行代码如下:

pig.fast_write(gg, 'hist_prog_cc_wheat_9', engine=new_pred, schema='prediction', mode='append')

该方法的参数说明为:

pig.fast_write(dataframe, tablename in database, engine, editmode)

但运行时出现如下错误:

InvalidTextRepresentation: invalid input syntax for type double precision: "2023-04-02"
CONTEXT:  COPY hist_prog_cc_wheat_9, line 1, column prediction_date: "2023-04-02"

我已确认DataFrame中prediction_date列的数据类型与数据库中对应列一致,请问该如何解决此问题?

解决方法
  • 核对列顺序与映射:自定义fast_write方法如果依赖列顺序匹配而非列名匹配,可能出现DataFrame的日期列被错误对应到数据库表的double precision类型列上。打印DataFrame的列顺序print(gg.columns),再对比数据库表prediction.hist_prog_cc_wheat_9的列顺序,确认prediction_date列的位置是否完全对应。
  • 显式指定列名映射:如果fast_write方法支持传入列名参数,调用时明确指定DataFrame列与数据库表列的对应关系,避免自动匹配出错。例如:
    pig.fast_write(gg, 'hist_prog_cc_wheat_9', engine=new_pred, schema='prediction', mode='append', columns=gg.columns.tolist())
    
  • 强制验证日期列类型:即使你认为类型一致,也可以再次确认并转换:
    gg['prediction_date'] = pd.to_datetime(gg['prediction_date']).dt.date
    
    确保列是Python的date类型,而非字符串或其他格式,避免自定义方法处理时出现类型转换错误。
  • 复查数据库表结构:再次确认数据库表prediction.hist_prog_cc_wheat_9的prediction_date列类型,是否确实是DATE或TIMESTAMP类型,而非double precision——可能存在表结构被意外修改,或者你查看的是其他schema下的同名表。
  • 排查fast_write的实现逻辑:如果有权限查看自定义类的代码,检查它在使用COPY命令时是否正确处理了日期列,比如是否将datetime类型错误转为字符串后,被PostgreSQL误判为数值类型输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:52:51