8

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())
Ugur
  • 1,914
  • 2
  • 25
  • 46
  • You can get this behavior without having to call ``display()`` on each data frame. See my answer below. – Nathaniel Mar 22 '19 at 19:55

1 Answers1

3

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

Nathaniel
  • 3,230
  • 11
  • 18
  • Doesn't work with large data frames with lots of columns. - How does Jupyter pretty print a dataframe? How can I make it print several dataframes / variables from within one cell? – Ugur Mar 22 '19 at 19:16