Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty print several variables in a Jupyter notebook cell

Jupyter notebooks (Python) return the value of the last variable in a cell in a pretty printed format.

Using print(df) won't output the dataframe pretty printed. But this will pretty print df to the Jupyter notebook:

In[1]:

import pandas as pd
import numpy as np

filename = "Umsaetze.csv"
csv_file = f"~/Desktop/{filename}"

# read csv into DataFrame
df = pd.read_csv(csv_file, sep=";", decimal=",")
df

How can I print several variables in a pretty printed format?

This here will only print df3 in a pretty printed format:

In[2]:

df1
df2
df3

Edit

Here is the answer (from: Show DataFrame as table in iPython Notebook)

from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print("Dataframe 1:")
display(df1.head())
print("Dataframe 2:")
display(df2.head())
like image 949
Ugur Avatar asked Mar 22 '19 18:03

Ugur


1 Answers

You can use tabulate to output a table in pretty-printed format:

import pandas as pd
import numpy as np
from tabulate import tabulate

df = pd.DataFrame(np.random.randint(0, 10, size=(5, 4)), columns = list('ABCD'))

print(tabulate(df, headers = 'keys', tablefmt = 'psql'))
+----+-----+-----+-----+-----+
|    |   A |   B |   C |   D |
|----+-----+-----+-----+-----|
|  0 |   2 |   1 |   3 |   0 |
|  1 |   1 |   9 |   1 |   6 |
|  2 |   9 |   8 |   6 |   3 |
|  3 |   0 |   7 |   3 |   2 |
|  4 |   5 |   9 |   7 |   3 |
+----+-----+-----+-----+-----+

Edit: To print multiple data frames in pretty-print format from a single cell in Jupyter Notebook, use the following:

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

df
df

Table Output

like image 55
Nathaniel Avatar answered Sep 24 '22 20:09

Nathaniel