You can convert SQLAlchemy ORM to pandas DataFrame using the read_sql
function of pandas.
import sqlalchemy as db
import pandas as pd
engine = db.create_engine('postgresql://username:password@host:port/database')
Note: Replace username
, password
, host
, port
and database
with your own values.
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.
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.
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!
Asked: 2022-10-30 11:00:00 +0000
Seen: 11 times
Last updated: Aug 23 '21