Jupyter Notebook在哪里/如何与python的repr/str挂钩 [英] Where/how does Jupyter notebook hook into python's repr/str
问题描述
[在jupyter笔记本中:python3内核]
[In jupyter notebook: python3 kernel]
如果我用熊猫制作数据框或用sympy制作矩阵,则打印效果非常好 即它看起来很像电子表格/矩阵等
If I make a data-frame in pandas or a matrix in sympy it prints very nicely ie it looks quite like a spreadsheet/matrix etc
它是如何做到的? 是谁做的?
How does it do it? Who does it?
数据帧在str/repr方法中似乎没有什么特别的地方(例如生成html). 在普通的python和jupyter中尝试过. Jupyter的印刷要复杂得多.
The data-frame does not seem to have anything special (eg generating html) in the str/repr methods. Tried in ordinary python and jupyter. Jupyter's printing is much more sophisticated.
那么它如何挂在哪里?
推荐答案
我只能为熊猫说话,但我认为sympy的工作方式与此类似.
I can only speak for pandas but I imagine sympy works in a similar way.
Pandas将DataFrame
转换为HTML字符串.如果我们打印此字符串,它看起来比仅打印DataFrame时还要糟糕.
Pandas converts a DataFrame
into an HTML string. If we print this string it it looks even worse than a when we just print a DataFrame.
from IPython.display import display, HTML
import pandas as pd
data = pd.DataFrame({'col': range(5)})
print(data._repr_html_())
'<div>\n<style scoped>\n .dataframe tbody tr....'
如果相反,我们使用Jupyter的HTML
进行显示,则Jupyter知道将其在Web浏览器中呈现为HTML,并因此显示为HTML表格.
If instead we use Jupyter's HTML
to display this, Jupyter knows to render this in the web browser as HTML and thus is is displayed as an HTML table.
HTML(data._repr_html_())
col
0 0
1 1
2 2
3 3
4 4
这篇关于Jupyter Notebook在哪里/如何与python的repr/str挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!