백엔드/Python
파이썬에서 dataframe to postgresql 저장하기
작은소행성
2021. 11. 21. 15:56
import sqlalchemy
from sqlalchemy import create_engine
engine = sqlalchemy.create_engine("postgresql://user:password@host:port/database")
df_tp.to_sql(name = 'tablename',
con = engine,
schema = 'public',
if_exists = 'replace', # {'fail', 'replace', 'append'), default 'fail'
index = True,
index_label = 'id',
chunksize = 2,
dtype = {
'id': sqlalchemy.types.INTEGER(),
'dominant': sqlalchemy.INTEGER(),
'contribution': sqlalchemy.types.Float(precision=3),
'topic': sqlalchemy.types.TEXT(),
'date': sqlalchemy.DateTime(),
'to_yn': sqlalchemy.types.Boolean(),
'docid': sqlalchemy.types.INTEGER()
})
- if_exists = 'fail' : 같은 이름의 Table이 존재할 경우 ValueError 가 남
- if_exists = 'replace': 같은 이름의 Table이 존재할 경우 기존 Table을 Drop하고 새로운 값을 Insert함
- if_exists = 'append': 같은 이름의 Table이 존재할 경우 기존 Table에 추가로 새로운 값을 Insert함
반응형