简体   繁体   English

熊猫to_sql尝试为可空列建立索引

[英]Pandas to_sql Trying to Index Nullable Column

I want to set up a job that dumps data into a SQL table every day, overwriting the existing data. 我想设置一个每天将数据转储到SQL表中的作业,以覆盖现有数据。

df.to_sql(table_name, engine, schema='dbo', 
          index=True, index_label='IdColumn', 
          if_exists='replace')

However behind the scenes SQLAlchemy is trying to create the table with IdColumn VARCHAR(max), and being nullable. 但是,SQLAlchemy在后台尝试使用IdColumn VARCHAR(max)创建表,并且该表可以为空。 So SQL throws an error when it tries to create the index. 因此,SQL在尝试创建索引时会引发错误。

It's pretty trivial to truncate the table before I write the data to it, but I feel like there should be a more elegant solution to this problem. 在向表写入数据之前截断表是很简单的,但是我觉得应该对此问题有一个更优雅的解决方案。

If you want the write the index to the sql table as a normal column, you can do a reset_index before the to_sql call: 如果你想要写索引到SQL表作为一个正常的列,你可以做一个reset_index的前to_sql拨打:

df.reset_index().to_sql(table_name, engine, schema='dbo', index=False, if_exists='replace')

The only problem is the name of that column, if you want a custom one you first have to set the index name ( df.index.name = 'IdColumn' ) or rename after the reset_index. 唯一的问题是该列的名称,如果要自定义列,则必须首先设置索引名称( df.index.name = 'IdColumn' )或在reset_index之后重命名。

Consider using the dtype argument which takes a dictionary mapping data frame column names to specified sqlalchemy data types . 考虑使用dtype参数,该参数采用将数据帧列名称映射到指定的sqlalchemy数据类型的字典。 You can try Varchar : 您可以尝试Varchar

import sqlalchemy

df.to_sql(table_name, engine, schema='dbo', 
          index=True, index_label='IdColumn', 
          if_exists='replace',
          dtype={'IdColumn': sqlalchemy.types.VARCHAR(length=255)})

or generic String type, specifying a length: 或通用String类型,指定长度:

from sqlalchemy.types import String

df.to_sql(table_name, engine, schema='dbo', 
          index=True, index_label='IdColumn', 
          if_exists='replace',
          dtype={'IdColumn': String(length=255)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM