SQLAlchemy ORM conversion to Pandas DataFrame
Last Updated :
22 Jun, 2022
In this article, we will see how to convert an SQLAlchemy ORM to Pandas DataFrame using Python.
We need to have the sqlalchemy as well as the pandas library installed in the python environment –
$ pip install sqlalchemy
$ pip install pandas
For our example, we will make use of the MySQL database where we have already created a table named students. You are free to use any database but you need to accordingly create its connection string. The raw SQL script for reference for this example is provided below:
CREATE DATABASE Geeks4Geeks;
USE Geeks4Geeks;
CREATE TABLE students (
first_name VARCHAR(50),
last_name VARCHAR(50),
course VARCHAR(50),
score FLOAT
);
INSERT INTO students VALUES
('Ashish', 'Mysterio', 'Statistics', 96),
('Rahul', 'Kumar', 'Statistics', 83),
('Irfan', 'Malik', 'Statistics', 66),
('Irfan', 'Ahmed', 'Statistics', 81),
('John', 'Wick', 'Statistics', 77),
('Mayon', 'Irani', 'Statistics', 55),
('Ashish', 'Mysterio', 'Sociology', 85),
('Rahul', 'Kumar', 'Sociology', 78),
('Irfan', 'Malik', 'Biology', 92),
('Irfan', 'Ahmed', 'Chemistry', 45),
('John', 'Wick', 'Biology', 78),
('Mayon', 'Irani', 'Physics', 78);
SELECT * FROM students;

The syntax for converting the SQLAlchemy ORM to a pandas dataframe is the same as you would do for a raw SQL query, given below –
Syntax: pandas.read_sql(sql, con, **kwargs)
Where:
- sql: The SELECT SQL statement to be executed
- con: SQLAlchemy engine object to establish a connection to the database
Please note that you can also use pandas.read_sql_query() instead of pandas.read_sql()
Example 1:
In the above example, we can see that the sql parameter of the pandas.read_sql() method takes in the SQLAlchemy ORM query as we may have defined it without the pandas dataframe conversion. The db.select() will get converted to raw SQL query when read by the read_sql() method. In the output, we have also printed the type of the response object. The output is a pandas DataFrame object where we have fetched all the records present in the student’s table.
Python3
import pandas
import sqlalchemy as db
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = db.create_engine("mysql + pymysql:\
/ / root:password@localhost / Geeks4Geeks")
class Students(Base):
__tablename__ = 'students'
first_name = db.Column(db.String( 50 ),
primary_key = True )
last_name = db.Column(db.String( 50 ),
primary_key = True )
course = db.Column(db.String( 50 ))
score = db.Column(db. Float )
df = pandas.read_sql_query(
sql = db.select([Students.first_name,
Students.last_name,
Students.course,
Students.score]),
con = engine
)
print ( "Type:" , type (df))
print ()
print (df)
|
Output:

Example 2:
In this example, we have used the session object to bind the connection engine. We have also applied a filter() method which is equivalent to the WHERE clause in SQL. It consists of the condition that the picked records should contain the first name and the last name of those students who have a score of greater than 80. One thing worth noting here is that, for the queries build using the session object, we need to use the statement attribute to explicitly convert into a raw SQL query. This is required because without the statement attribute, it will be a sqlalchemy.orm.query.Query object which cannot be executed by the pandas.read_sql() method and you will get a sqlalchemy.exc.ObjectNotExecutableError error. The above output shows the type of object which is a pandas DataFrame along with the response.
Python3
import pandas
import sqlalchemy as db
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = db.create_engine("mysql + pymysql:\
/ / root:password@localhost / Geeks4Geeks")
class Students(Base):
__tablename__ = 'students'
first_name = db.Column(db.String( 50 ),
primary_key = True )
last_name = db.Column(db.String( 50 ),
primary_key = True )
course = db.Column(db.String( 50 ))
score = db.Column(db. Float )
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()
df = pandas.read_sql_query(
sql = session.query(Students.first_name,
Students.last_name). filter (
Students.score > 80 ).statement,
con = engine
)
print ( "Type:" , type (df))
print ()
print (df)
|
Output:

Similar Reads
Converting Django QuerySet to Pandas DataFrame
Django's ORM provides a powerful way to query databases and retrieve data using QuerySet objects. However, there are times when you may need to manipulate, analyze, or visualize this data in a more sophisticated way than what Django alone can offer. In such cases, pandas, a popular data manipulation
6 min read
Connecting Pandas to a Database with SQLAlchemy
In this article, we will discuss how to connect pandas to a database and perform database operations using SQLAlchemy. The first step is to establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = crea
3 min read
Create a SQL table from Pandas dataframe using SQLAlchemy
In this article, we will discuss how to create a SQL table from Pandas dataframe using SQLAlchemy. As the first steps establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = create_engine(dialect+driv
3 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing
3 min read
Conversion Functions in Pandas DataFrame
.numpy-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .numpy-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padding: 8px; } .numpy-table td:nth-child(odd) { background-color: #c6ebd9; } .numpy-table
5 min read
Converting Pandas Crosstab into Stacked DataFrame
In this article, we will discuss how to convert a pandas crosstab to a stacked dataframe. A stacked DataFrame is a multi-level index with one or more new inner levels as compared to the original DataFrame. If the columns have a single level, then the result is a series object. The panda's crosstab f
4 min read
How to convert pandas DataFrame into SQL in Python?
In this article, we aim to convert the data frame into an SQL database and then try to read the content from the SQL database using SQL queries or through a table. Convert Pandas DataFrame into SQL in PythonBelow are some steps by which we can export Python dataframe to SQL file in Python: Step 1: I
4 min read
How to get column names from SQLAlchemy?
In this article, we will discuss how to get column names using SQLAlchemy in Python. SQLAlchemy is an open-source SQL toolkit and object-relational mapper for the Python programming language released under the MIT License. It gives full power and flexibility of SQL to an application. To follow along
3 min read
Convert PySpark Row List to Pandas DataFrame
In this article, we will convert a PySpark Row List to Pandas Data Frame. A Row object is defined as a single Row in a PySpark DataFrame. Thus, a Data Frame can be easily represented as a Python List of Row objects. Method 1 : Use createDataFrame() method and use toPandas() method Here is the syntax
4 min read
How to convert Dictionary to Pandas Dataframe?
A dictionary, with its key-value structure, can easily be transformed into a DataFrame, a tabular format. Default Pandas DataFrame constructor is the most versatile and straightforward method to convert a dictionary into a DataFrame. Method 1: Using Pandas Constructor By passing the dictionary direc
3 min read