PandasでPostgreSQLを操作する
/
PandasでPostgreSQLを操作します.
# PandasでPostgreSQLを操作する
# テーブル作成とデータ格納
import os
import psycopg2
from sqlalchemy import create_engine
# DBのURL
DATABASE_URL='postgresql://postgre:postgre@workspace-postgres-1:5432/postgres'
# テーブル作成のDB起動
engine = create_engine(DATABASE_URL)
# テーブル作成 if_exists='replace' or 'append'
df.to_sql('probe',con=engine,if_exists='replace',index=None)
# dbとカーソルを閉じる
engine.close()
# データの出力(DF)
import os
import psycopg2
from sqlalchemy import create_engine
# DBのURL
DATABASE_URL='postgresql://postgre:postgre@workspace-postgres-1:5432/postgres'
# postgresの接続
conn = psycopg2.connect(DATABASE_URL)
print(conn.autocommit)
# テーブル情報の抽出
df1=pd.read_sql(sql='SELECT * FROM probe;', con=conn)
display(df1.head())
print(len(df1))
# dbとカーソルを閉じる
conn.close()
# まとめ
PandasでPostgreSQLを操作しました.
# 参考サイト
pandas で sqlite3 の読み書き (opens new window)
【 コピペでOK】9割の機能を網羅!PytonからPostgreSQLを扱うクラスを作ってみました。 (opens new window)
PandasのDataFrameでPostgreSQLに読み書きする方法 (opens new window)