【问题标题】:Insert a pandas dataframe into a SQLite table将 pandas 数据框插入 SQLite 表
【发布时间】:2019-04-10 20:37:50
【问题描述】:

所以我有一个从 excel 导入的数据框和一个带有匹配列的 SQL 表。到目前为止,我一直在使用列作为列表来更新表格:

Schedule_Frame = DataFrame(Sheet_Schedule)

Column_ID=Schedule_Frame['ID']

Column_list=list(Column_ID)


for i in range(len(Column_list)):

miCursor.execute("UPDATE SCHEDULE SET ID=? WHERE rowid=?",(Column_list[i],i))

但是,由于我在 SQLite 中拥有的是一个与我的数据框列匹配的表,我确信有一种方法可以使用我的框架更新整个 SQLite 表。

有什么办法吗?

非常感谢!!

【问题讨论】:

    标签: python sql pandas sqlite dataframe


    【解决方案1】:

    我认为您正在使用 sqlite3 包来访问您的 SQLite 数据库。使用SQLAlchemy(与 Pandas 的数据结构配合得很好)来访问数据库怎么样?

    from sqlalchemy import create_engine
    engine = create_engine('sqlite:///<replace_this_with_path_to_db_file>', echo=False)
    

    然后做:

    Schedule_Frame.to_sql('SCHEDULE', con=engine, if_exists='append')
    

    编辑:示例代码

    from sqlalchemy import create_engine
    import pandas as pd
    
    engine = sqlalchemy.create_engine('sqlite:///my.db', echo=False)
    df = pd.DataFrame([[1,2],[1,2]], columns=['a', 'b'])
    
    df.to_sql('mytable', con=engine, if_exists='append')
    

    在 sqlite3 CLI 中:

    sqlite> select * from 'mytable';
    0|1|2
    1|1|2
    

    资源:

    【讨论】:

    • 感谢您的回复!当我转到它并将我的代码插入为: from sqlalchemy import create_engine engine = create_engine('sqlite://C:/Users/Javier/Desktop/Holidays Tool/Scheduler RES', echo=False) Schedule_Frame.to_sql('SCHEDULE ', con=engine, if_exists='append') 我收到以下错误:ValueError: invalid literal for int() with base 10: '' 有什么想法吗?
    • 您确定您的路径指向数据库文件(通常数据库文件有.db 后缀)?我用一个虚拟的 DataFrame 运行了我建议的代码,一切都很完美。您的错误表明您的架构可能与 DataFrame 的架构不同。
    • 非常感谢!我用它作为你的,它工作。我现在得到的唯一错误是关于索引:sqlite3.OperationalError: table SCHEDULE has no column named index 你知道我是否可以更改代码中的某些内容,这样它就不会尝试在数据库中的表中添加索引列吗? ?
    猜你喜欢
    • 2018-02-27
    • 2016-07-17
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多