【问题标题】:Pandas - Looping through multiple items in a Dataframe to a SQL queryPandas - 将 Dataframe 中的多个项目循环到 SQL 查询
【发布时间】:2020-07-29 07:08:33
【问题描述】:

我有一个包含两列的 Dataframe,一列提到 product_name,另一列包含与该产品相关的键,如下所示:

product,key
prod_a, key_1
prod_b, key_2
prod_c, key_3

我正在尝试查询一个表,以便在 where 子句中应用产品及其对应的键,如下所示:

查询:

cursor.execute("""select prod_name, quantity from table where prod_name = {product} and prod_key = {key}""")

productkey 的值取自上述 Dataframe

我想将上述 DataFrame 中的每个产品和键循环到 SQL 查询广告中获取输出

【问题讨论】:

  • 你不要将产品和密钥作为列表传递给cursor.execute 并使用where prod_name IN [list_items] 吗?

标签: sql pandas


【解决方案1】:

itertuples() 是更快的方法。

for index, row in df.itertuples():
    cursor.execute("""select prod_name, quantity from table where prod_name = '{row["product"]}' and prod_key = '{row["key"]}'""")

.itertuples() 为每一行生成一个命名元组,其中包含行的索引 value 作为元组的第一个元素。

.iterrows() 为中的每一行生成 (index, Series) 的对(元组) 数据框。

您可以阅读更多关于它的信息here

【讨论】:

    【解决方案2】:

    使用以下方法计算:

    for index, row in df.iterrows():
        print(index, row["product"],row["key"])
    
        cursor.execute(f"""select prod_name, quantity from table where prod_name = '{row["product"]}' and prod_key = '{row["key"]}'""")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 2018-07-16
      • 2021-01-25
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 2023-04-11
      相关资源
      最近更新 更多