在Jupyter笔记本单元中漂亮地打印几个变量

时间:2019-03-22 18:53:29

标签: python jupyter-notebook

Jupyter笔记本(Python)以漂亮的打印格式返回单元格中最后一个变量的值。

使用print(df)不会输出漂亮打印的数据框。但这会在Jupyter笔记本上漂亮地打印df

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

如何以漂亮的打印格式打印几个变量?

这将仅以漂亮的打印格式打印df3

In[2]:

df1
df2
df3

编辑

这是答案(来自: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())

1 个答案:

答案 0 :(得分:2)

您可以使用tabulate以漂亮的打印格式输出表格:

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 |
+----+-----+-----+-----+-----+

编辑:要从Jupyter Notebook的单个单元中以漂亮打印格式打印多个数据框,请使用以下命令:

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

df
df

Table Output