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)

    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

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

Disable warnings

import warnings


# 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


Suppress warnings

See above: Disable warnings

Dialogue & Discussion