使用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
相关产品推荐
相关产品推荐

