熊猫to_sql()更新数据库中的唯一值?


问题内容

如何使用df.to_sql(if_exists = 'append')来在数据框和数据库之间仅附加唯一值。换句话说,我想评估DF和DB之间的重复项,并在写入数据库之前删除这些重复项。

为此有参数吗?

据我所知,参数if_exists = 'append'if_exists = 'replace'对整个表-而不是唯一条目。

I am using: 
sqlalchemy

pandas dataframe with the following datatypes: 
    index: datetime.datetime <-- Primary Key
    float
    float
    float
    float
    integer
    string <---  Primary Key
    string<----  Primary Key

我坚持这样做,非常感谢您的帮助。-谢谢


问题答案:

在pandas中,没有方便的参数to_sql可以将非重复项附加到最终表中。考虑使用熊猫 总是
替换的临时临时表,然后运行最终追加查询以将临时表记录迁移到最终表,仅考虑使用该NOT EXISTS子句的唯一PK 。

engine = sqlalchemy.create_engine(...)

df.to_sql(name='myTempTable', con=engine, if_exists='replace')

with engine.begin() as cn:
   sql = """INSERT INTO myFinalTable (Col1, Col2, Col3, ...)
            SELECT t.Col1, t.Col2, t.Col3, ...
            FROM myTempTable t
            WHERE NOT EXISTS 
                (SELECT 1 FROM myFinalTable f
                 WHERE t.MatchColumn1 = f.MatchColumn1
                 AND t.MatchColumn2 = f.MatchColumn2)"""

   cn.execute(sql)

这将是ANSI SQL解决方案,并且不限于特定于供应商的方法UPSERT,因此实际上与所有SQL集成的关系数据库兼容。