繁体   English   中英

在 MySQL 数据库中保存 pandas dataframe 的最快方法是什么

[英]What is the fastest way to save a pandas dataframe in a MySQL Database

我正在 python 中编写代码,以基于来自另一个数据库的另一个 mysql 表生成和更新 mysql 表。

我的代码是这样的:

对于 date_range 中的日期:

  1. 在 db1 中查询两个日期之间的数量

  2. 在 pandas => df 中做一些工作

  3. 在 db2 中删除 df 中 id 的行

  4. 用 df.to_sql 保存 df

操作 1-2 耗时不到 2s,而操作 3-4 最多耗时 10s。 第 4 步比第 3 步多花 4 倍。如何改进我的代码以使编写过程更高效

我已经为第 3 步和第 4 步分块了 df。我在.to_sql中添加了method=multi (这根本不起作用)。 我想知道我们是否可以做得更好;

with db.begin() as con:
    for chunked in chunks(df.id.tolist(), 1000):
        _ = con.execute(""" DELETE FROM table where id 
                            in {} """.format(to_tuple(chunked)))
    for chunked in chunks(df.id.tolist(), 100000):        
        df.query("id in @chunked").to_sql('table', con, index=False, 
        if_exists='append')

感谢您的帮助

我发现df.to_sql非常慢。 One way that I've gotten around it this issue is by outputting the dataframe into a csv file with df.to_csv and using BCP in to bluk insert the data in the csv into the table then deleting the csv file once its done with the insertion . 您可以使用子进程在 python 脚本中运行 BCP。

暂无
暂无

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

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