Python on Jupyter notebooks: Reference for Common Use Cases

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Add commands to the beginning of notebooks

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)

    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 current 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'>

Show Python executable path

import sys

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

Get Python interpreter path

Same as above:

import sys

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

Get Python version

from platform import python_version

python_version()
# '3.6.7'

Enable autoreload

Use this to make your testing life easier.

%load_ext autoreload

%autoreload 2

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

Dialogue & Discussion