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
- last_expr: only print the last statement if it is an expression (default) — returns nothing twice
- none: print nothing — returns nothing twice
- last: prints the last expression, even if it is in a loop, without a nextline character. — returns nothing and ‘2468’
- last_expr_or_assign: Print the last expression or assignment. Only for simple variables. It doesn’t work when you assign a value to a position in an array. — returns ’12’ and nothing
- all: prints all expressions without a nextline character. — returns ‘106’
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!