【问题标题】:Python. Optimize Append DF to MySQL DBPython。优化 Append DF to MySQL DB
【发布时间】:2018-10-24 14:22:29
【问题描述】:

我在数据库中添加这样的模型输出:

cursor = conn.cursor()
for i in range(len(df)):
    UserId = df.loc[i, 'UserId']
    Timestamp = df.loc[i, 'Timestamp']
    ChurnPropensity = df.loc[i, 'ChurnPropensity']

    sql = "INSERT INTO DB_Name (UserId, Timestamp, ChurnPropensity) VALUES ({},'{}',{});".format(UserId, Timestamp, ChurnPropensity)

    cursor.execute(sql)

conn.commit()

但是,由于 for 循环,它需要很长时间。您将如何缩短计算时间?

敬礼,

【问题讨论】:

  • 桌子有多大?您是否尝试过使用pd.DataFrame.to_sql
  • 我实际上有,但没有设法正确设置“create_engine”位。该表有几千行,但我希望它能够轻松扩展。
  • 设法让pd.DataFrame.to_sql 工作,时间减少了 90% :)
  • 太棒了。但我认为由于 I/O 的原因,即使使用 to_sql,批量插入仍然存在瓶颈。您可以尝试构建原始查询,然后使用 sqlalchemy 来执行它们。但这很有帮助!

标签: python mysql sql python-3.x pandas


【解决方案1】:

试试这个方法。理想情况下,它应该加快执行速度。

query = "INSERT INTO DB_Name (UserId, Timestamp, ChurnPropensity) VALUES ({},'{}',{});"
df.apply(lambda row: cursor.execute(query.format(row['UserId'], 
                                                 row['Timestamp'], 
                                                 row['ChurnPropensity'])),
axis=1)

根据我的经验,execute 方法本身很慢,所以你可以加快 尝试一次执行多个查询。

query = "INSERT INTO DB_Name (UserId, Timestamp, ChurnPropensity) VALUES ({},'{}',{});"
queries_list = df.apply(lambda row: query.format(row['UserId'], 
                                            row['Timestamp'], 
                                            row['ChurnPropensity']),  axis=1).values.tolist()

queries = ' '.join(queries_list)
cursor.execute(queries, multi=True)

【讨论】:

  • 谢谢!但它需要相同的时间。
  • 意外的关键字参数'multi'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
  • 2023-04-07
  • 1970-01-01
  • 2022-12-27
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
相关资源
最近更新 更多