Site icon Roel Peters

Jupyter Notebooks: How to print multiple outputs in a cell

On my list of things that frustrate me when using notebooks is the fact that you do not see the output of every expression of a cell by default. For example, during an exploratory analysis phase, I want to see the result of two pandas operations or function within the same cell, because they belong to each other.

Luckily, there’s a Jupyter setting that you can change to print multiple outputs.

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'

The ast_node_interactivity setting allows you to choose which results are shown as outputs. By setting it to ‘all’, every assign and expression will be shown. If that’s too much for you, here are the other options. I demonstrate what every option will return with two chunks of example code.

5 + 5
3 + 3
my_var = 6 + 6
10 - 10
for i in range(1,5):
    i * 2

As you can see. Not all options are useful for simple expressions because the output of all expressions gets concatinated. Yet when you work with data frames, they will be aligned vertically, below each other.

In Google Colab, you cannot change the setting to last_expr_or_assign — it will crash your kernel. There’s a simple workaround: by installing the latest version of IPython, you will get access to the option.

!pip install -U ipython 

Another problem solved!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Exit mobile version