Django Pandas Integration

0.6.7 · active · verified Thu Apr 16

django-pandas provides tools to seamlessly integrate Django models with Pandas DataFrames. It allows you to query your Django models and return the results directly as Pandas DataFrames, simplifying data analysis, reporting, and machine learning workflows within Django projects. As of version 0.6.7, it's actively maintained with releases focused on compatibility with recent Django and Pandas versions.

Common errors

Warnings

Install

Imports

Quickstart

To use django-pandas, add `objects = DataFrameManager()` to your Django model. Then, you can call `.to_dataframe()` on your model's manager or any QuerySet to convert the results into a Pandas DataFrame. Remember to ensure your Django app is configured and migrations are run.

from django.db import models
from django_pandas.managers import DataFrameManager

# Define a simple Django model
class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField(default=0)
    last_updated = models.DateTimeField(auto_now=True)

    # Attach DataFrameManager to your model
    objects = DataFrameManager()

    def __str__(self):
        return self.name

# --- Usage example (in a Django shell or view) ---
# Make sure to run migrations for the Product model first.
# from myapp.models import Product # Assuming Product is in 'myapp'
# Product.objects.create(name='Laptop', price=1200.00, stock=50)
# Product.objects.create(name='Mouse', price=25.50, stock=200)

# Fetch data directly as a Pandas DataFrame
# df = Product.objects.to_dataframe()
# print(df.head())

# You can also filter before converting to DataFrame
# low_stock_df = Product.objects.filter(stock__lt=100).to_dataframe()
# print(low_stock_df)

view raw JSON →