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数据帧,而不是两者的salaries和teams.如果我只是运行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)
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]部分.
枚举所有解决方案:
sys.displayhook(value),IPython/jupyter 挂钩。请注意,这与调用的行为略有不同display,因为它包含Out[n]文本。这在普通 python 中也能正常工作!
get_ipython().ast_node_interactivity = 'all'。这与此答案所采用的方法类似但更好。
在交互式会话中比较这些:
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 中的行为完全相同。
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)
| 归档时间: |
|
| 查看次数: |
24539 次 |
| 最近记录: |