【问题标题】:What is the fasted way to insert a pandas data frame into a database with the same columns?将熊猫数据框插入具有相同列的数据库中的最快方法是什么?
【发布时间】:2021-05-28 23:08:25
【问题描述】:

假设我有一个数据框 df,它具有与 sql 表相同的列。 将数据框插入表中的最简单(也是最有效的方法)是什么。

import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session

df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
engine = create_engine('sqlite:///database.db')
conn = engine.connect()

Base = automap_base()
Base.prepare(engine, reflect=True)
session = Session(bind=engine)

# No assume that the database has a table Users with one column "name" 
# is there a function, which adds all entries of the dataframe to the sql table?
# This should also works with dates/floats type of columns and multiple columns

【问题讨论】:

    标签: python pandas sqlalchemy


    【解决方案1】:

    最简单的方法? 只需使用

    df.to_sql('tableName', databaseConnectionObject, if_exists='append')
    

    我也觉得效率高,但不能说是不是效率最高,需要自己去测试

    【讨论】:

    • 这是一个梦想 :)
    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2018-03-21
    • 2020-11-29
    • 2013-10-23
    • 2020-07-20
    • 2013-04-05
    • 1970-01-01
    相关资源
    最近更新 更多