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

使用Pandas向MySQL插入explode拆分数据时遇OperationalError报错

解决Pandas拆分列表后插入MySQL的Operand错误

修复后的代码

import pandas as pd

tactic_theme = pd.read_csv(link, usecols=(0, 7))
tactic_theme.columns = ['code_tac', 'code_th']

# 拆分字符串为列表后,将explode的结果赋值回原DataFrame
tactic_theme['code_th'] = tactic_theme.code_th.str.split(" ")
tactic_theme = tactic_theme.explode('code_th')

tactic_theme.to_sql('tactic_themes', con=engine, if_exists='replace', index=False, chunksize=1000)

问题分析

  • 核心错误:explode()是非原地修改方法,调用后会返回一个新的DataFrame,不会改变原对象。你之前仅调用tactic_theme.explode('code_th')但未将结果赋值,导致原tactic_theme的code_th列仍为列表类型。
  • MySQL表的code_th列是单值字段(如VARCHAR),无法存储Python列表,因此触发(1241, 'Operand should contain 1 column(s)')错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:10:50