【问题标题】:How to put Dataframe into SQL where clause using Python?如何使用 Python 将 Dataframe 放入 SQL where 子句中?
【发布时间】:2020-09-04 12:15:07
【问题描述】:

我有一个 Panda Dataframe df

索引 ID 0‘123’, 1'234', 2'456', 3'686', 4‘777’

我想用 Python 编写代码:

import pyodbc
conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
Query = "select * from table1 where ID in ????????"   

我想做'?'直接获取我的 df,我应该如何实现?

【问题讨论】:

    标签: sql python-3.x


    【解决方案1】:

    使用where 后,您应该列出一个列表,据我所知,您可以替换 ?与df.values.reshape(-1,1) 为此,取决于您的 python 版本:

    f"select * from table1 where ID in {df.values.reshape(-1,1)}"
    

    '''select * from table1 where ID in {df.values.reshape(-1,1)}'''
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2022-06-16
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      相关资源
      最近更新 更多