在iPython Notebook中将DataFrame显示为表

问题描述 投票:177回答:5

我正在使用iPython笔记本。当我这样做:

df

我得到一张带细胞的美丽桌子。但是,如果我这样做:

df1
df2 

它不会打印出第一张漂亮的桌子。如果我试试这个:

print df1
print df2

它以不同的格式打印出表格,使列溢出并使输出非常高。

有没有办法强制它打印出两个数据集的漂亮表格?

pandas printing ipython-notebook jupyter-notebook display
5个回答
312
投票

您需要使用IPython显示模块中的HTML()display()函数:

from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))

请注意,如果您只是print df1.to_html(),您将获得原始的,未呈现的HTML。

您也可以从IPython.core.display导入具有相同的效果


43
投票
from IPython.display import display
display(df)  # OR
print df.to_html()

35
投票

这个答案是基于这篇博文的第二个提示:28 Jupyter Notebook tips, tricks and shortcuts

您可以将以下代码添加到笔记本的顶部

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

这告诉Jupyter在它自己的行上打印任何变量或语句的结果。因此,您可以执行仅包含的单元格

df1
df2

它将“打印出两个数据集的漂亮表格”。


6
投票

我不喜欢搞乱HTML并尽可能多地使用原生基础设施。您可以将输出小部件与Hbox或VBox一起使用:

import ipywidgets as widgets
from IPython import display
import pandas as pd
import numpy as np

# sample data
df1 = pd.DataFrame(np.random.randn(8, 3))
df2 = pd.DataFrame(np.random.randn(8, 3))

# create output widgets
widget1 = widgets.Output()
widget2 = widgets.Output()

# render in output widgets
with widget1:
    display.display(df1)
with widget2:
    display.display(df2)

# create HBox
hbox = widgets.HBox([widget1, widget2])

# render hbox
hbox

这输出:

enter image description here


4
投票

看来你可以在显示中使用逗号显示两个dfs。我在github上的一些笔记本上注意到了这一点。此代码来自Jake VanderPlas的笔记本。

class display(object):
    """Display HTML representation of multiple objects"""
    template = """<div style="float: left; padding: 10px;">
    <p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1}
    </div>"""
    def __init__(self, *args):
        self.args = args

    def _repr_html_(self):
        return '\n'.join(self.template.format(a, eval(a)._repr_html_())
                     for a in self.args)

    def __repr__(self):
        return '\n\n'.join(a + '\n' + repr(eval(a))
                       for a in self.args)

display('df', "df2")

© www.soinside.com 2019 - 2024. All rights reserved.