1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pandas: PostgreSQL のテーブルの更新

Posted at

プログラム

postgre_drop.py
#! /usr/bin/python
#
#	postgre_drop.py
#
#					Aug/28/2024
# ------------------------------------------------------------------
import sys
import pandas as pd
#
from sqlalchemy import create_engine
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
engine = create_engine('postgresql://scott:tiger123@127.0.0.1/city')
#
df=pd.read_sql_query('SELECT * FROM cities', con=engine)
print(df)
print(df.shape)
#
try:
	dg = df.drop([0,1,2,3])
	print(dg)
	print(dg.shape)
	try:
		dg.to_sql(name='cities',con=engine,if_exists='replace', index=True)
	except Exception as ee:
		sys.stderr.write("*** error *** in db.to_sql ***\n")
		sys.stderr.write(str(ee) + "\n")

except Exception as ee:
	sys.stderr.write("*** error *** in df.drop ***\n")
	sys.stderr.write(str(ee) + "\n")
#
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行結果

1回目

$ ./postgre_drop.py
*** 開始 ***
       0    1      2           3
0  t1271   千葉  58471   2003-9-25
1  t1272   勝浦  49523   2003-3-16
2  t1273   市原  27461   2003-6-21
3  t1274   流山  39872   2003-8-27
4  t1275  八千代  21576   2003-11-5
5  t1276  我孫子  53271   2003-1-12
6  t1277   鴨川  81326   2003-5-22
7  t1278   銚子  95142  2003-10-18
(8, 4)
       0    1      2           3
4  t1275  八千代  21576   2003-11-5
5  t1276  我孫子  53271   2003-1-12
6  t1277   鴨川  81326   2003-5-22
7  t1278   銚子  95142  2003-10-18
(4, 4)
*** 終了 ***

2回目

$ ./postgre_drop.py
*** 開始 ***
   index      0    1      2           3
0      4  t1275  八千代  21576   2003-11-5
1      5  t1276  我孫子  53271   2003-1-12
2      6  t1277   鴨川  81326   2003-5-22
3      7  t1278   銚子  95142  2003-10-18
(4, 5)
Empty DataFrame
Columns: [index, 0, 1, 2, 3]
Index: []
(0, 5)
*** 終了 ***

参考ページ

pandas で PostgreSQL の読み書き

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?