Skip to content

Instantly share code, notes, and snippets.

@joaopmatias
joaopmatias / upsert_df.py
Last active July 6, 2023 15:18 — forked from pedrovgp/upsert_df.py
Allow upserting a pandas dataframe to a postgres table (equivalent to df.to_sql(..., if_exists='update')
# Upsert function for pandas to_sql with postgres
# https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291
# https://www.postgresql.org/docs/devel/sql-insert.html#SQL-ON-CONFLICT
import uuid
import os
import pandas as pd
import sqlalchemy
from sqlalchemy import create_engine, types, Engine, text