使用更新记录到

2024-04-26 14:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Pandas将文本文件中的df与sql数据库中的df进行比较。如果要插入的文本文件df中的项目不同,或者如果数据库中已有该项目,请更新该字段。你知道吗

# Text File
# "Id","Stock_ID","Colour"
# "298","203","Green"

df1 = pd.read_table("data.txt", sep = ",")
df2 = pd.read_sql_table("mytable", con=engine)


df3 = pd.concat([df2, df1], sort=False).drop_duplicates(subset = . 
["Stock_ID"], keep=False)
df4 = df3.loc[pd.isnull(df3.id)] # This contains the new record to update

df4.to_sql('feed', con=engine, if_exists='replace', index_label='id', 
dtype={
    'id': sqlalchemy.INTEGER(), 
})

df4.to_sql抛出一个错误ValueError: duplicate name in index/columns: cannot insert id, already exists。你知道吗

如何按id更新数据库中的行?你知道吗


Tags: to项目id数据库dfreadsqlstock