python - 从 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 编写更新代码来更新数据库的最佳方法是什么?
解决方案
您可以尝试将 df 写入数据库中pandas
的temp
表,然后使用 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)
推荐阅读
- r - 如何修复“文件错误(文件,“rt”):无法打开连接
- java - spring data jpa:更新@many边表后,无法通过findAll @one边表以相同的方法获得正确的更改
- python - 如何链接多个组合框表中的两个组合框?
- python - 为什么BERT中的矩阵叫Query、Key和Value?
- sql-server - 具有 Entity Framework Core 的表分区
- database - 在数据库中存储多个企业的开放和关闭时间的最佳方法是什么
- javascript - 响应式语音 js 如何与 Promise 一起工作?
- javascript - JavaScript中条件中的匿名函数
- javascript - 仅在静态生成的页面 Nuxt.js 中存在编码问题
- microsoft-graph-api - 尝试获取用户拥有所有权的团队列表