首页 > 解决方案 > 从 Python 中的 DataFrame 更新 sql 中的一列

问题描述

使用 pandas,我使用以下内容从 sql 中读取查询:

df = pd.read_sql(query, engine) 

这个数据框非常大,我通过一些计算更新了一个名为“权重”的列。

我想要的是用 DataFrame 中的新列更新该列。我该怎么做才能使列更新对应于正确的行?

例如,假设我有一个像这样的样本 df:df =

 type color  size weight
 10  green  12     13
 23  green  40     10 
 16    red  40     15 

其中 df['weight'] 是我要在数据库中更新的新计算的列。

db 目前看起来像这样: Table =

 type color  size weight
 10  green  12     null
 23  green  40     null 
 16    red  40     null 

我预期的 sql 更新表是这样的:

 type color  size weight
 10  green  12     13
 23  green  40     10 
 16    red  40     15 

我正在使用psychopg2,下面是我对代码的思考过程:

UPDATE table 
SET weight = df.weight
WHERE table.type = df.type
AND table.size = df.size
AND table.color = df.color 

用 Python 编写更新代码来更新数据库的最佳方法是什么?

标签: pythonsqlpandas

解决方案


您可以尝试将 df 写入数据库中pandastemp表,然后使用 sql 创建匹配的列

connect=('yourconnectionfordb')
df.to_sql('test', connect, if_exists='replace')

query = "UPDATE table AS f" + \
      " SET weight = test.weight" + \
      " FROM test AS t" + \
      " WHERE f.type = t.type " + \
      " AND f.size = t.size" + \
      " AND f.color = t.color"

with connect.begin() as conn:
   conn.execute(query)

推荐阅读