Python on Jupyter notebooks: Reference for Common Use Cases

Python on Jupyter notebooks: Reference for Common Use Cases

Last updated:
Table of Contents

Add commands to all notebooks

In order to add a set of commands that will be run as the first cell in all notebooks you create, do this:

Ubuntu OS is assumed

  • Create a profile:

    $ ipython profile create
    [ProfileCreate] Generating default config file: '/home/felipe/.ipython/profile_default/ipython_config.py'
    [ProfileCreate] Generating default config file: '/home/felipe/.ipython/profile_default/ipython_kernel_config.py'
    
  • 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
    pd.set_option('display.max_columns',100)
    pd.set_option('display.max_rows',100)
    
    # for text columns
    pd.set_option('display.max_colwidth',500)
    pd.set_option('display.html.use_mathjax',False)
    
  • Provided you have pandas, numpy and matplotlib installed, these will be available for every notebook you create.

List 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])

%whos
# 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/__init__.py'>

Python executable path

Get path to current Python executable that was used to launch jupyter:

import sys

sys.executable
# '/home/felipe/venv36/bin/python3'

Python interpreter path

Same as above:

import sys

sys.executable
# '/home/felipe/venv36/bin/python3'

Python version

To print the Python version in use in this notebook:

from platform import python_version

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