python - 从 pandas 数据帧批量更新 peewee 数据库的最有效方法
问题描述
数据库如下所示:
date value
2000-01-01 foo
2000-01-01 foo
2000-01-01 foo
2000-01-02 bar
2000-01-02 bar
2000-01-02 bar
2000-01-10 yyy
2000-01-10 yyy
2000-01-10 yyy
Pandas 数据框MyDataframe
如下所示:
date value
2000-01-01 new_foo
2000-01-02 new_bar
2000-01-10 new_yyy
正如您可能已经猜到的那样,我需要数据库看起来像这样:
date value
2000-01-01 new_foo
2000-01-01 new_foo
2000-01-01 new_foo
2000-01-02 new_bar
ecc...
我可以循环MyDataframe
并运行一系列.update
:
for date, value in MyDataframe:
query = MyModel.update(value=value).where(MyModel.date == date).execute()
query.execute()
我的问题是:有没有办法通过一次调用execute()
(或任何其他更有效的方式)来做到这一点?像bulk_execute(array_of_queries)
什么?
有没有办法将数据框直接提供给 .update()?像这样:
MyModel.update(value=MyDataframe.loc[MyModel.date]).execute()
不幸的是,这不起作用:传递给的索引.loc[]
不是实际值,而是一个DateTimeField
对象。事实上,它给出了这个错误:
KeyError('the label [<DateTimeField: MyModel.date>] is not in the [index]',)
该文档建议您可以在更新函数中运行实际代码,并提供以下示例:
Employee.update(bonus=(Employee.bonus + (Employee.salary * .1)))
解决方案
您可以尝试合并数据框并替换原始值列。
推荐阅读
- ruby-on-rails - Rails 中的“方法:”参数仅用于删除操作吗?
- asp.net-core - 无法验证 'id_token',找不到合适的 ISecurityTokenValidator:''。”
- python - 使用 Pandas 在现有 Excel 文件中的指定索引处插入工作表
- html - 自定义 ol li 缩进
- javascript - 理解 javascript 中的 for 循环
- jenkins - 如何在 jenkins 中启动服务器以并行运行验收测试?
- facebook - 什么是 fbclid?新的 facebook 参数
- kotlin - kotlin - 如何覆盖哈希码
- jsf - 发送多个ajax请求的问题
- java - FlyWay .... 无法解析位置类路径:db/migration