Skip to Content

Technology Blog

Technology Blog

Django shell_plus with Pandas, and Jupyter Notebook

Recently updated on

Our environment will be setup inside a virtual environment using Django 2.2.  Once inside the virtual environment, install IPython, Jupyter, Pandas, django-extensions, and django-pandas.

  1. pip install ipython jupyter pandas django-extensions django-pandas

django-extensions needs to be placed into INSTALLED_APPS in your settings.py file.

  1. INSTALLED_APPS = [
  2.     ...
  3.     'django_extensions',
  4. ]

Once installed, then run

  1. python manage.py shell_plus --notebook

shell_plus is Django shell with autoloading of the apps database models and subclasses of user-defined classes. The --notebook argument tells shell_plus to open in a Jupyter notebook.

You will notice that a new Jupyter tab opens in your browser. In the upper right corner click on the New drop-down and select Django Shell-Plus.

A new tab will open and you will see your new Jupyter notebook.  Import django-pandas read_frame.

Let's explore our new and improved shell environment by interacting with the following models.

  1. class Movie(models.Model):
  2. title = models.CharField(max_length=100)
  3. year = models.IntegerField()
  4. def __str__(self):
  5. return f"{self.title} ({self.year})"
  6. class Actor(models.Model):
  7. name = models.CharField(max_length=100)
  8. movies = models.ManyToManyField('Movie')
  9. def __str__(self):
  10. return self.name

Lets say we want to explore Tom Hanks movies.  We pass read_frame a QuerySet, and it returns a Pandas DataFrame.  Now, of course, you can bring all the powers of Pandas to bear on your data.

For a basic example,  lets say we want to see all of his movies after 2015, in alphabetical order.

It is true that something similar could be done without pandas, but it isn't nearly as clean and concise, and you would just be trying to recreate what pandas already does so well.

Whether you use Pandas or not, since your code exists in Jupyter notebook cells, there is no need to scroll through the shell history to reuse/change code snippets.

The above is just a taste of what can be done in this environment.

Further reading:

Jupyter Notebook Tutorial

Pandas Tutorial

Pandas and SQL Tutorial

Jentacular


Share , ,
If you're getting even a smidge of value from this post, would you please take a sec and share it? It really does help.