从 Pandas df 更新数据库中的现有行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29607222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update existing row in database from pandas df
提问by darkpool
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.
我有一个 PostgreSQL 数据库。Pandas 有一个“to_sql”函数可以将数据帧的记录写入数据库。但是我还没有找到任何关于如何在我完成数据帧后使用 Pandas 更新现有数据库行的文档。
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.
目前,我可以使用 pandas read_sql_table 将数据库表读入数据帧。然后我会根据需要处理数据。但是我一直无法弄清楚如何将该数据帧写回数据库以更新原始行。
I dont want to have to overwrite the whole table. I just need to update the rows that were originally selected.
我不想覆盖整个表。我只需要更新最初选择的行。
回答by johan855
One way is to make use of an sqlalchemy "table class" and session.merge(row), session.commit():
一种方法是使用 sqlalchemy“表类”和 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()

