Loading SQL tables into pandas DataFrames bridges relational databases and Python’s data analysis ecosystem, offering key benefits:
- Rich data manipulation functions
- Easy integration with visualization libraries
- 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)