从pandas数据框批量更新peewee数据库的最有效方法

问题描述 投票:1回答:1

数据库看起来像这样:

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

熊猫数据框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]',)

documentation建议您可以在更新函数中运行实际代码,提供以下示例:

Employee.update(bonus=(Employee.bonus + (Employee.salary * .1)))
python pandas peewee
1个回答
-1
投票

您可以尝试合并数据框并替换原始值列。

© www.soinside.com 2019 - 2024. All rights reserved.