LoginSignup
19
19

More than 5 years have passed since last update.

[python] pandasのDataFrameからpostgresにテーブルを作成

Last updated at Posted at 2016-03-09

pandasのDataFrameからtableを作成するメモ
DataFrameをそのままto_sqlすると、postgresにはインサートできなかった

before.py
import pandas as pd
import psycopg2


db = "dbname=postgres host=localhost user=username"
conn = psycopg2.connect(db)

df = pd.read_csv("sample.csv")
df.to_sql(df,"table_name", conn, if_exist="replace", index=False)

いろいろ調べた結果、sqliteへの書き込みがデフォルトらしいので変更

after.py
import pandas as pd
from sqlalchemy import create_engine


df = pd.read_csv("sample.csv")
engine=create_engine("postgresql://username@hostname:port/dbname")
df.to_sql("table_name", engine, if_exist="replace", index=False)

read_sqlはbeforeのやり方で問題なかった

参考>http://stackoverflow.com/questions/23103962/how-to-write-dataframe-to-postgres-table

19
19
1

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
19
19