2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pandas df.to_sqlのプライマリキー

Last updated at Posted at 2021-03-23

困りごと

Pandasのdataframeをsqliteに保存しようとしています。

いくつかのEXCELシートをdfに入れた後、df.to_sqlの追加操作でappendしております。

その際に、index_label='id' を指定すると、
テーブルを空にしている状態では、問題なくidが生成しますが、
さらに別のデータを追加しようとすると、idが最初から振り直されてしまいます。

このid列をプライマリーキーにして、すでにある連番とは異なるユニークな値になるようにして、
書き込むには、どうすればよいのでしょうか?

別のPandas からの書き込み方法があれば、df.to_sql以外でも結構です。

def df_write_to_sql(df,model,mode="replace"): #省略時は置き換えとする、アペンド時はmode="append"とすること

    df.to_sql(name=name,con=engine,if_exists=mode,index_label='id')

一つ目のデータ

0	AP	AD
1	AP	AD
...
258	ORS	OTH
259	ORS	PL
260	ORS	DI
261	ORS	EX

二つ目のデータ 

0	AP	C-L   → 262として書き込みたい
1	AP	C-L   → 263  〃
2	AP	C-L   → 264  〃
3	AP	C-L   → 265  〃

解決策

丸1日悩んで結論を得た。

下記が参考になった。
https://stackoverflow.com/questions/54808848/pandas-to-sql-increase-tables-index-when-appending-dataframe

ポイント

  • プライマリーキーにオートインクリースをつける
  • to_sqlのindex=Falseにする

こうすると、pandasはindexを無視してDBに書き込むことになる。
→ そもそもPKと言うものは、データベース側に委ねるというのがセオリーであった。
It would be nice to have a way to delegate auto-indexing to the database.

 id = db.Column(db.Integer, primary_key=True,autoincrement=True)
 df.to_sql(name=name,con=engine,if_exists="append",index=False)
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?