简体   繁体   English

pandas df.to_sql 如果列值退出替换或更新行

[英]pandas df.to_sql if column value exits replace or update row

I'm using pandas df.to_sql to inserting rows to postgresql database.我正在使用 pandas df.to_sql 将行插入 postgresql 数据库。

df.to_sql('example_table', engine, if_exists='replace',index=False)

example_table has 3 columns:'id','name','datetime' example_table 有 3 列:'id','name','datetime'

I want to add a checking logic before inserting,that if the datetime is already exits,then replace or update the exiting row.我想在插入之前添加一个检查逻辑,如果日期时间已经存在,则替换或更新退出行。

Is there something like:有没有类似的东西:

df.to_sql('example_table', engine, if_ datetime_exists='replace',index=False)

There is no if_exist sql function. Try this instead:没有if_exist sql function。试试这个:

# Create a DataFrame with the rows you want to insert
df_to_insert = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie'], 'datetime': ['2022-01-01', '2022-01-02', '2022-01-03']})

# Read the existing rows from the database into a DataFrame
df_existing = pd.read_sql_query('SELECT * FROM example_table', engine)

# Merge the two DataFrames, using the "datetime" column as the key
df_merged = pd.merge(df_to_insert, df_existing, on='datetime', how='left')

# Replace the values in the merged DataFrame with the values from the to_insert DataFrame
# where the "datetime" column is null (indicating that it is a new row)
df_merged.loc[df_merged['datetime'].isnull(), ['name', 'datetime']] = df_to_insert.values

# Write the merged DataFrame to the database
df_merged.to_sql('example_table', engine, if_exists='replace', index=False)

This will insert datetime in db if not already there also will update existing rows in case of missing datetime .这将在 db 中插入日期时间(如果还没有的话)也会在缺少日期时间的情况下更新现有行。

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

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