我将 MySQL 与 pandas 和 sqlalchemy 一起使用。然而,它的速度非常慢。对于一个包含 1100 万行的表,一个简单的查询需要 11 分钟以上才能完成。哪些行动可以改善这种表现?提到的表没有主键,并且仅由一列索引。
from sqlalchemy import create_engine
import pandas as pd
sql_engine_access = 'mysql+pymysql://root:[password]@localhost')
sql_engine = create_engine(sql_engine_access, echo=False)
script = 'select * from my_database.my_table'
df = pd.read_sql(script, con=self.sql_engine)
您可以尝试我们的工具连接器x https://github.com/sfu-db/connector-x (pip install -U connectorx
)。它是用 Rust 实现的,旨在提高pandas.read_sql
。 API 基本相同pandas
。例如,在您的情况下,代码将如下所示:
import connectorx as cx
conn_url = "mysql://root:[password]@localhost:port/my_database"
query = "select * from my_table"
df = cx.read_sql(conn_url, query)
如果查询结果中有像 ID 一样均匀分布的数字列,您还可以通过利用多个核心来进一步加快该过程,如下所示:
df = cx.read_sql(conn_url, query, partition_on="ID", partition_num=4)
这将通过过滤将整个查询分成四个小查询ID
列和connectorx
将并行运行它们。您可以查看here https://github.com/sfu-db/connector-x#examples了解更多用法和示例。
Here is the benchmark result loading 60M rows x 16 columns from MySQL to pandas DataFrame using 4 cores:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)