Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert SQL database table to a DataFrame with SQLAlchemy’s ORM

In a Flask app, I would like to convert an SQL Lite database table (User here) to a DataFrame.
I have tried this

df = pd.DataFrame(dict(r) for r in User.query.all())

but it returns the error 'User' object is not iterable.

I’m not very familiar with SQLAlchemy. What would be a correct statement?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this

from your_flask_app import db
from your_flask_app.models import User
import pandas as pd

users = User.query.all()

user_dicts = [user.__dict__ for user in users]

for user_dict in user_dicts:
    user_dict.pop('_sa_instance_state', None)

df = pd.DataFrame(user_dicts)

print(df.head())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading