首页 > 解决方案 > 将 pandas df 写入 sql dB 的新列不适用于追加

问题描述

尝试使用 pandas/sql alchemy 进行一些自学。我在本地系统上设置了一个虚拟 dB ms SQL 2012(我们在工作中使用的 dB),我可以

从中读取数据

从现有的 dB 创建一个表(测试了多达 500 万行整数和短字符串,大约需要 9 分钟)

更新它并追加新行

将所有目标行替换为df with if_exists='replace'

现在我无法弄清楚,这可能是由于我的无知是如何将带有附加列的数据帧写入我的 dB。

取以下 df,我将从我的 dB 中提取

   stores = np.random.choice(800,5,replace=True)
week1 = np.random.randint(1,500,size=5)
df = pd.DataFrame({'Stores' : stores,'Week 1' : week1})
    print(df)
    Stores  Week 1
0   461 413
1   568 181
2   793 173
3   349 49
4   713 258

现在,如果我想用现有列和新行更新它,这可以按预期完美工作,但是如果我创建一个新列:

df['Week 2'] = np.random.randint(1,500,size=len(df)) 

使用时出现以下错误:

df.to_sql(name='my table',
con = engine,
index=False,
if_exists='append')



    ProgrammingError: ('42S22', "[42S22] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'Week 2'. (207) (SQLExecDirectW); [42S22] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'Week 2'. (207); [42S22] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")

The above exception was the direct cause of the following exception:

一如既往地非常感谢任何帮助/文档指导。

标签: pythonsql-serverpandas

解决方案


如错误描述中所述,“Week 2”是Mysql中不可接受的表列名称“Invalid column name 'Week 2'”。,

ProgrammingError: ('42S22', "[42S22] [Microsoft][SQL Server Native Client 11.0][SQL Server] Invalid column name 'Week 2' . (207) (SQLExecDirectW); [42S22] [Microsoft][SQL Server Native客户端 11.0][SQL Server]列名“1956”无效。 (207);[42S22][Microsoft][SQL Server Native Client 11.0][SQL Server]无法准备语句。(8180)")

将其更改为(例如)Week2,它应该可以正常工作。

df['Week2'] = np.random.randint(1,500,size=len(df)) 

它还将“1956”视为列名,但我不知道这是否是因为先前的错误,所以请先更正这个;)


推荐阅读