繁体   English   中英

从单个列的 Pandas 数据框创建 SQL 中的大型“In”语句

[英]Creating Large "In" Statements in SQL from a Pandas Dataframe from a Single Column

我有一个非常典型的用例,我得到了大型 CSV/Excel 文件,并要求我对特定列进行 Hive 查询。

该用例要求我使用该特定列中的数据在 Hive 查询中创建非常大的“IN”语句。 这并不令人讨厌,但我非常想减少我在其中任何一个中的触摸和错误率,因此手动执行它们是不可取的。

glue_sql()我一直在使用 R 的glue_sql()函数,但需要将我的工作流转换为Python。

它在 Glue::glue_sql() 中的工作方式是这样的:

CSV 列名称是“用户名”。 您在 CSV 中读取为“df”。

然后为所需列中的数据定义一个变量: lotsofnames <- df$username

您将 sql 写为"select * from table where customer in ({lotsofnames*})

从那里你做glue_sql(query) ,它自动地使你从你在lotsofnames分配的值正确格式化的“in”语句。

我的大问题是:目前是否有一个 Python 包可以做到这一点?

如果有,我的 google-fu 没有找到它,“glue”已经是 Python 中一个非常不同的包的名称。

我看到了这个答案,但它没有做我需要的。

如果没有,是否有一个已经存在的功能可以做到这一点?
时间/生产力节省将在很大程度上证明将我的工作流程转换为 Python 的时间成本是合理的。

提前致谢!

我过去遇到过这个问题。 我使用sqlalchemy.and_sqlalchemy.or_的组合解决了它:

import sqlachemy as sa

# Let's say you want to find all the Mr. Smith and Ms. Elliott
params = pd.DataFrame({
    'Title': ['Mr.', 'Ms.'],
    'LastName': ['Smith', 'Elliott']
})

# Setting up the connection
engine = sa.create_engine('...')
meta = sa.MetaData(engine)

# Get the table's structure from the database. I'm accessing the
# `Person.Person` table in the AdventureWorks sample DB in SQL Server. You may
# not need to specify the `schema` keyword for your use case
table = sa.Table('Person', meta, schema='Person', autoload_with=engine)

# Here's the magic: `or_` down the rows, `and_` across the columns.
# `table.c.LastName` refers to column LastName in `table`
cond = sa.or_(*[
    sa.and_(table.c.Title == row['Title'], table.c.LastName == row['LastName'])
        for _, row in params.iterrows()
])

# Get Title, FirstName, MiddleName and LastName from rows matching the
# conditions
result = sa.select([
    table.c.Title,
    table.c.FirstName,
    table.c.MiddleName,
    table.c.LastName,
]).where(cond).execute()

# You can turn the result into a DataFrame if you want
result_df = pd.DataFrame(result, columns=result.keys())

结果:

Title FirstName MiddleName LastName
  Ms.     Carol         B.  Elliott
  Ms.   Shannon         P.  Elliott
  Mr.   Leonard         J.    Smith
  Mr.   Rolando         T.    Smith
  Mr.      Jeff       None    Smith
  Mr.    Mahesh       None    Smith
  Mr.     Frank       None    Smith

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM