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!
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-10-30 11:00:00 +0000
Seen: 11 times
Last updated: Aug 23 '21
How can the SQL debug mode be activated in PostgreSQL version 15.2?
What is the procedure for using pg_restore on Windows with Docker?
What is the equivalent of SQL Server NVARCHAR in PostgreSQL?
What is the method to retrieve the JSON data from a column in SQL?
How to solve the issue of being unable to establish a connection with libpq on Mac M1?
Is it possible to launch multiple instances of PostgreSQL using Spring Boot Testcontainers?
Due to SyntaxError, why am I unable to create a TIMESTAMP WITH TIMEZONE column in postgres?