Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update existing row in database from pandas df

Tags:

I have a PostgreSQL db. Pandas has a 'to_sql' function to write the records of a dataframe into a database. But I haven't found any documentation on how to update an existing database row using pandas when im finished with the dataframe.

Currently I am able to read a database table into a dataframe using pandas read_sql_table. I then work with the data as necessary. However I haven't been able to figure out how to write that dataframe back into the database to update the original rows.

I dont want to have to overwrite the whole table. I just need to update the rows that were originally selected.

like image 960
darkpool Avatar asked Apr 13 '15 14:04

darkpool


People also ask

Can we modify a data inside a DataFrame?

Although DataFrames are meant to be populated by reading already organized data from external files, many times you will need to somehow manage and modify already existing columns (and rows) in a DF.


1 Answers

One way is to make use of an sqlalchemy "table class" and session.merge(row), session.commit():

Here is an example:

for row in range(0, len(df)):     row_data = table_class(column_1=df.ix[i]['column_name'],                            column_2=df.ix[i]['column_name'],                            ...                            )     session.merge(row_data)     session.commit() 
like image 61
johan855 Avatar answered Oct 26 '22 23:10

johan855