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

%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

import sys

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

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

Disable warnings

import warnings

warnings.filterwarnings('ignore')

# no warnings will be printed

Disable warnings matching text

Example: Disable warnings whose message text match 'foo bar'

import warnings

warnings.filterwarnings('ignore', message='foo bar')

# no warnings matching 'foo bar' will be printed

Enable warnings

For example, re-enable warnings disabled by the command above

import warnings

warnings.filterwarnings('default')

Suppress warnings

See above: Disable warnings

Dialogue & Discussion