【问题标题】:Creating Large "In" Statements in SQL from a Pandas Dataframe from a Single Column从单个列中的 Pandas 数据框在 SQL 中创建大型“In”语句
【发布时间】:2021-02-21 18:29:47
【问题描述】:

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

该用例要求我使用该特定列中的数据在 Hive 查询中创建非常大的“IN”语句。这并不令人讨厌,但我非常想降低我在其中任何一个中的触摸和错误率,所以手工操作是不可取的。

为此,我一直在使用 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 中一个非常不同的包的名称。

我看到this answer, but it doesn't do what I need.

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

提前致谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我过去遇到过这个问题。我使用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
    

    【讨论】:

      猜你喜欢
      • 2018-03-05
      • 2015-09-13
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多