IPython 笔记本电池多输出

IPython Notebook cell multiple outputs

我运行在 IPython 笔记本中使用这个单元格:

# salaries and teams are Pandas dataframe
salaries.head()
teams.head()

结果是我只得到 teams 数据帧的输出,而不是 salariesteams 的输出。如果我只是 运行 salaries.head() 我得到 salaries 数据帧的结果但是在 运行 上我只看到 teams.head() 的输出。我该如何纠正?

IPython 笔记本仅显示单元格中的最后一个 return 值。最简单的解决方案是使用两个单元格。

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

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

A()

如果你经常需要这个,把它做成一个函数:

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

用法:

show_two_heads(salaries, teams)

两个头以上的版本:

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

用法:

show_many_heads(salaries, teams, df1, df2)

提供,

print salaries.head()
teams.head()

你试过display命令了吗?

from IPython.display import display
display(salaries.head())
display(teams.head())

更简单的方法:

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

它使您不必重复输入 "Display"

假设单元格包含这个:

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

a = 1
b = 2

a
b

那么输出将是:

Out[1]: 1
Out[1]: 2

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

from IPython.display import display

a = 1
b = 2

display(a)
display(b)

输出为:

1
2

同样的事情,但没有 Out[n] 部分。

枚举所有解:

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

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

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

如果您使用打印功能,这会起作用,因为只给直接命令 returns 最后一个命令的输出。 例如,

salaries.head()
teams.head()

仅针对 teams.head()

输出

print(salaries.head())
print(teams.head())

两个命令的输出。

所以,基本上,使用 print() 函数