IPython Notebook单元格多输出

Lok*_*esh 62 ipython pandas ipython-notebook

我在IPython Notebook中运行这个单元格:

# salaries and teams are Pandas dataframe
salaries.head()
teams.head()
Run Code Online (Sandbox Code Playgroud)

其结果是,我只得到的输出teams数据帧,而不是两者的salariesteams.如果我只是运行salaries.head()我得到salaries数据帧的结果,但在运行两个语句我只看到输出teams.head().我怎么能纠正这个?

tgl*_*ria 98

你试过这个display命令吗?

from IPython.display import display
display(salaries.head())
display(teams.head())
Run Code Online (Sandbox Code Playgroud)

  • 从文档:"因为IPython 5.4和6.1`display()`自动可供用户使用而无需导入." (11认同)

Aru*_*ngh 73

更简单的方法:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Run Code Online (Sandbox Code Playgroud)

它可以节省你不得不重复键入"显示"

假设单元格包含:

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

a = 1
b = 2

a
b
Run Code Online (Sandbox Code Playgroud)

然后输出将是:

Out[1]: 1
Out[1]: 2
Run Code Online (Sandbox Code Playgroud)

如果我们使用IPython.display.display:

from IPython.display import display

a = 1
b = 2

display(a)
display(b)
Run Code Online (Sandbox Code Playgroud)

输出是:

1
2
Run Code Online (Sandbox Code Playgroud)

所以同样的事情,但没有Out[n]部分.

  • 您应该使用 `get_ipython().ast_node_interactivity = 'all'`,而不是用常量字符串替换类属性! (3认同)
  • 哦,我希望我能回答。我记得几个月前在另一个问题上看到了它(希望我能提供),它对我来说效果很好,所以我把它放在了后兜里。 (2认同)

Eri*_*ric 7

枚举所有解决方案:

在交互式会话中比较这些:

In [1]: import sys

In [2]: display(1)          # appears without Out
   ...: sys.displayhook(2)  # appears with Out
   ...: 3                   # missing
   ...: 4                   # appears with Out
1
Out[2]: 2
Out[2]: 4

In [3]: get_ipython().ast_node_interactivity = 'all'

In [2]: display(1)          # appears without Out
   ...: sys.displayhook(2)  # appears with Out
   ...: 3                   # appears with Out (different to above)
   ...: 4                   # appears with Out
1
Out[4]: 2
Out[4]: 3
Out[4]: 4
Run Code Online (Sandbox Code Playgroud)

请注意,Jupyter 中的行为与 ipython 中的行为完全相同。


Mik*_*ler 5

IPython Notebook 仅显示单元格中的最后一个返回值。对于您的情况,最简单的解决方案是使用两个单元。

如果你真的只需要一个单元格,你可以这样做:

class A:
    def _repr_html_(self):
        return salaries.head()._repr_html_() + '</br>' + teams.head()._repr_html_()

A()
Run Code Online (Sandbox Code Playgroud)

如果你经常需要这个,请将其设为一个函数:

def show_two_heads(df1, df2, n=5):
    class A:
        def _repr_html_(self):
            return df1.head(n)._repr_html_() + '</br>' + df2.head(n)._repr_html_()
    return A()
Run Code Online (Sandbox Code Playgroud)

用法:

show_two_heads(salaries, teams)
Run Code Online (Sandbox Code Playgroud)

两个以上头的版本:

def show_many_heads(*dfs, n=5):
    class A:
        def _repr_html_(self):
            return  '</br>'.join(df.head(n)._repr_html_() for df in dfs) 
    return A()
Run Code Online (Sandbox Code Playgroud)

用法:

show_many_heads(salaries, teams, df1, df2)
Run Code Online (Sandbox Code Playgroud)