Skip to content

Instantly share code, notes, and snippets.

@maxcrom
Forked from kunanit/pandas_postgres.py
Created March 31, 2021 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxcrom/68b38b10ebb77d5997df480c2febaf08 to your computer and use it in GitHub Desktop.
Save maxcrom/68b38b10ebb77d5997df480c2febaf08 to your computer and use it in GitHub Desktop.
Read postgres database table into pandas dataframe
import pandas as pd
from sqlalchemy import create_engine
# follows django database settings format, replace with your own settings
DATABASES = {
'production':{
'NAME': 'dbname',
'USER': 'user',
'PASSWORD': 'pass',
'HOST': 'rdsname.clqksfdibzsj.us-east-1.rds.amazonaws.com',
'PORT': 5432,
},
}
# choose the database to use
db = DATABASES['production']
# construct an engine connection string
engine_string = "postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}".format(
user = db['USER'],
password = db['PASSWORD'],
host = db['HOST'],
port = db['PORT'],
database = db['NAME'],
)
# create sqlalchemy engine
engine = create_engine(engine_string)
# read a table from database into pandas dataframe, replace "tablename" with your table name
df = pd.read_sql_table('tablename',engine)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment