pandas.to_sql用新列到现有表,自动添加新列?

时间:2016-07-13 14:14:27

标签: pandas sqlalchemy

我想将数据帧写入现有的sqlite(或mysql)表,有时数据帧将包含数据库中尚不存在的新列。我需要做些什么才能避免这种错误?有没有办法告诉pandas或sqlalchemy自动扩展具有潜在新列的数据库表?

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) table match_exact_both has no column named ....

2 个答案:

答案 0 :(得分:0)

如果数据框中有额外的列,则需要手动将该列添加到数据库表中,以使df.to_sql()生效。

答案 1 :(得分:0)

这是我使用mySQL和sqlalchemy的解决方案。基本思想是,如果可能的话,我想追加到SQL数据库而不是重新编写整个内容,但是如果有新列,则可以将Pandas中的数据合并,然后覆盖现有数据库。

import pymysql
from sqlalchemy import create_engine
import pandas as pd
cnx = create_engine('mysql+pymysql://username:password@hostname/database_name')
try:
    #this will fail if there is a new column
    df.to_sql(name='sql_table', con=cnx, if_exists = 'append', index=False)
except:
    data = pd.read_sql('SELECT * FROM sql_table', cnx)
    df2 = pd.concat([data,df])
    df2.to_sql(name='sql_table', con=cnx, if_exists = 'replace', index=False)