Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas to_sql fails on duplicate primary key

Tags:

I'd like to append to an existing table, using pandas df.to_sql() function.

I set if_exists='append', but my table has primary keys.

I'd like to do the equivalent of insert ignore when trying to append to the existing table, so I would avoid a duplicate entry error.

Is this possible with pandas, or do I need to write an explicit query?

like image 891
ryantuck Avatar asked May 19 '15 22:05

ryantuck


People also ask

How do I fix duplicate values in a primary key constraint?

When you use SQL Server you'll get a SQL error when you enter a duplicate value into a table that has a primary key constraint. You can fix it by altering your table: CREATE TABLE [dbo].

Is it possible to replace a record in a pandas Dataframe?

Pandas DataFrame.to_sql method has limitation of not being able to "insert or replace" records, see e.g: pandas-dev/pandas#14553 Using pandas.io.sql primitives, however, it's not too hard to implement such a functionality (for the SQLite case only).

Should append_skipdupes be added to the primary key column?

Yes, please. 'append_skipdupes' should be added and not only for the Primary Key column. If there are duplicates among other Unique columns also it should skip appending those new duplicate rows. Sorry, something went wrong. Sorry, something went wrong.

Can I skip appending duplicate rows to a column?

If there are duplicates among other Unique columns also it should skip appending those new duplicate rows. Sorry, something went wrong. Sorry, something went wrong. Sorry, something went wrong.


1 Answers

There is unfortunately no option to specify "INSERT IGNORE". This is how I got around that limitation to insert rows into that database that were not duplicates (dataframe name is df)

for i in range(len(df)):     try:         df.iloc[i:i+1].to_sql(name="Table_Name",if_exists='append',con = Engine)     except IntegrityError:         pass #or any other action 
like image 155
NFern Avatar answered Sep 19 '22 20:09

NFern