How to Load SQL Tables into Pandas DataFrames

Loading SQL tables into pandas DataFrames bridges relational databases and Python’s data analysis ecosystem, offering key benefits:

  1. Rich data manipulation functions
  2. Easy integration with visualization libraries
  3. Compatibility with machine learning libraries

To read a SQL table into a pandas DataFrame, pass the database connection obtained from the SQLAlchemy Engine to the pandas.read_sql method.

import pandas as pd
import sqlalchemy

# Create a SQLAlchemy engine
engine = sqlalchemy.create_engine(
    "postgresql://username:password@host:port/database_name"
)


# Read a SQL table into a DataFrame
df = pd.read_sql("SELECT * FROM table_name", engine)
Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran