简体   繁体   中英

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

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

表输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM