Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can convert SQLAlchemy ORM to pandas DataFrame using the read_sql function of pandas.

  1. Import the necessary libraries:
import sqlalchemy as db
import pandas as pd
  1. Create a database engine:
engine = db.create_engine('postgresql://username:password@host:port/database')

Note: Replace username, password, host, port and database with your own values.

  1. Execute a SQL query and retrieve the results as a pandas DataFrame:
df = pd.read_sql('SELECT * FROM table_name', engine)

Note: Replace table_name with the name of the table you want to retrieve data from.

  1. You can also execute more complex SQL queries that join multiple tables, perform aggregations, or apply filters:
df = pd.read_sql('''
    SELECT customers.customer_id, customers.name, orders.order_id, orders.date, order_items.product, order_items.quantity, order_items.price
    FROM customers
    JOIN orders ON customers.customer_id = orders.customer_id
    JOIN order_items ON orders.order_id = order_items.order_id
    WHERE orders.date BETWEEN '2021-01-01' AND '2021-12-31'
''', engine)

Note: This query retrieves data from three tables (customers, orders, order_items) and applies a filter on a date column.

  1. Once you have the data in a pandas DataFrame, you can perform further data analysis, cleaning, or visualization:
df.head()
df.describe()
df.groupby('name')['quantity'].sum().sort_values(ascending=False).head(10)
df.plot(kind='scatter', x='price', y='quantity')

Note: These are just examples of what you can do with pandas. The possibilities are endless!