Python on Jupyter notebooks: Reference for Common Use Cases

Last updated:
Table of Contents

Add commands to beginning of notebooks

Ubuntu OS is assumed

  • Create a profile:

    $ ipython profile create
    [ProfileCreate] Generating default config file: '/home/felipe/.ipython/profile_default/'
    [ProfileCreate] Generating default config file: '/home/felipe/.ipython/profile_default/'
  • Create a file under ~/.ipython/profile_default/startup/00-load.ipy with the following contents (this is just an example)

    # sample cell to be run at the beginning of every notebook
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    # general options
    # for text columns
  • Provided you have pandas, numpy and matplotlib installed, these will be available for every notebook you create.

List current variables

To list the currently defined variables, type %whos:

import numpy as np

a = np.array([1,2,3])
b = np.array([0,0,0])

# Variable   Type       Data/Info
# -------------------------------
# a          ndarray    3: 3 elems, type `int64`, 24 bytes
# b          ndarray    3: 3 elems, type `int64`, 24 bytes
# np         module     <module 'numpy' from '/ho<...>kages/numpy/'>

Python executable path

import sys

# '/home/felipe/venv36/bin/python3'

Python interpreter path

Same as above:

import sys

# '/home/felipe/venv36/bin/python3'

Get Python version

from platform import python_version

# '3.6.7'

Enable autoreload

Use autoreload to force the use of the updated code without the need for restarting the kernel

%load_ext autoreload

%autoreload 2

# antyhing you import from now on will be reloaded before you use it

Dialogue & Discussion