【问题标题】:How to insert multiple dataframes to sql server using iterrows?如何使用 iterrows 将多个数据帧插入到 sql server?
【发布时间】:2022-12-11 00:08:01
【问题描述】:

注意:在这种情况下我不能使用 executemany 它需要是一个拆分成多个 dfs 的数据帧。

dfooc 是我的原始数据框,我将其拆分为多个较小的 df。

我试过了:

import pyodbc
import numpy as np

a, b, c, d, e, f = np.array_split(dfooc, 6)

conn = pyodbc.connect("dsn=SNOWFLAKE_ENGINEER_SA;" "Trusted_Connection=yes;")
cursor = conn.cursor()
for index, row in a.iterrows():
    cursor.execute("INSERT INTO python.agefromname_incremental (OwnerId,ProbabilityMale, ProbableGender, ModeBirthYear,ProbableGeneration) values(?,?,?,?,?)", row.OwnerId,row.ProbabilityMale,row.ProbableGender,row.ModeBirthYear,row.ProbableGeneration)
for index, row in a.iterrows():
    cursor.execute("INSERT INTO python.agefromname_incremental (OwnerId,ProbabilityMale, ProbableGender, ModeBirthYear,ProbableGeneration) values(?,?,?,?,?)", row.OwnerId,row.ProbabilityMale,row.ProbableGender,row.ModeBirthYear,row.ProbableGeneration)
for index, row in b.iterrows():
    cursor.execute("INSERT INTO python.agefromname_incremental (OwnerId,ProbabilityMale, ProbableGender, ModeBirthYear,ProbableGeneration) values(?,?,?,?,?)", row.OwnerId,row.ProbabilityMale,row.ProbableGender,row.ModeBirthYear,row.ProbableGeneration)
for index, row in c.iterrows():
    cursor.execute("INSERT INTO python.agefromname_incremental (OwnerId,ProbabilityMale, ProbableGender, ModeBirthYear,ProbableGeneration) values(?,?,?,?,?)", row.OwnerId,row.ProbabilityMale,row.ProbableGender,row.ModeBirthYear,row.ProbableGeneration)
conn.commit()

但正如您所看到的,我必须为每个数据帧执行此操作,并且可能需要很长时间才能继续添加,因为我需要最终将 dfooc 数据帧拆分为 50 个 dfs。

有没有一种方法可以在一行中完成,比如for index, row in a,b,c,d,e,f.iterrows()

【问题讨论】:

    标签: python pandas numpy for-loop iteration


    【解决方案1】:

    这是使用 list comprehension 执行此操作的一种方法:

    cursor = conn.cursor()
    for row in [row for df in np.array_split(dfooc, 6) for _, row in df.iterrows()]:
        cursor.execute(
            "INSERT INTO python.agefromname_incremental (OwnerId,ProbabilityMale, ProbableGender, ModeBirthYear,ProbableGeneration) values(?,?,?,?,?)",
            row.OwnerId,
            row.ProbabilityMale,
            row.ProbableGender,
            row.ModeBirthYear,
            row.ProbableGeneration,
        )
    conn.commit()
    

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 2023-04-04
      • 2022-12-12
      • 2019-12-21
      • 1970-01-01
      • 2012-09-20
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多