0
0

More than 1 year has passed since last update.

DataFrameのto_sql()を使っていたが、Upsertを簡単に行いたかったので、datasetに変更した

Pandas.DataFrame.to_sql()には現在Upsertが備わっていない(PRはある)ので、簡単にUpsertするために、datasetに変更。
参考: PandasのSql Upsertを試してみた

CSV操作がかなり入るので、Upsert直前までは、DataFrameを使いたい。

DataFrame.to_sql() → dataset.upsert_many()に変更

参考: dataset documentation
bulkのupsertがありそうだったので、以下を利用したいと思いました。
upsert_many(rows,id)
upsert_manyの中身は、upsert()が呼ばれている。

以下をドキュメントから読み取るのに少し手間取ったのでメモ

  • rows:dict型
  • id:配列

DataFrameからupsert_manyに渡すdictをどのように作るか悩んだのでメモ

Seriesで取り出してto_dictで一行一行upsertするのかな?などと思ったが、

DataFrame.to_dict(orient = 'records')

でDataFrameをレコードっぽくdictにしてくれたので、以下で一括Upsertが完了

records = df.to_dict(orient = 'recods')
upsert_many(records,['key1','key2'])

DataFrame理解度の問題でした。。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0