【问题标题】:SQL Alchemy dynamically compare subset of columns to Pandas DataFrameSQLAlchemy 动态地将列的子集与 Pandas DataFrame 进行比较
【发布时间】:2020-02-04 02:44:00
【问题描述】:

我想将 SQL Server 表的行与 Pandas DataFrame 的行进行比较。我只比较某些列(构成表主键的列)。因此我不知道要提前比较多少列。我想修改以下内容以处理复合主键(作为字符串列表输入。)目前这只能处理比较一列,如果事先知道它们可以修改为处理多个但我希望它能够动态工作.

# Build the WHERE clause of your DELETE statement from rows in the dataframe.
cond = df_update_partial.apply(lambda row: sa.and_(detail_table.c[key_col] == row[key_col]), axis=1) 
     # trying to fix the above, right now it is set up to handle a single string column name
cond = sa.or_(*cond)

# Define and execute the DELETE
delete = detail_table.delete().where(cond)
with engine.connect() as conn:
    conn.execute(delete)

因此,上面有问题的行可能需要如下所示:

cond = df_update_partial.apply(lambda row: sa.and_(detail_table.c[key_col[0]] == row[key_col[0]], detail_table.c[key_col[1]] == row[key_col[1]], detail_table.c[key_col[2]] == row[key_col[2]]), axis=1) 
     # above is for a primary key made up of 3 columns. key_col is a list of these columns names.

但是如果我事先不知道这个列表的长度,我就不能这样设置。

最初找到的代码here

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    Python 有一个用于列表的东西,称为字典比较

    row_one = ...
    row_two = ...
    
    list(row_one) == list(row_two)
    # true if equally long AND all elements are the same
    

    你应该可以用这个

    【讨论】:

    • 我不想比较两个列表。我正在尝试使用列表中的项目创建表达式的结合。
    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    相关资源
    最近更新 更多