您可以使用 Javascript 打开一个新窗口,由 HTML 从 IPython.display 执行。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
# Show in Jupyter
df
from IPython.display import HTML
s = '<script type="text/Javascript">'
s += 'var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));'
s += 'win.document.body.innerHTML = \'' + df.to_html().replace("\n",'\\') + '\';'
s += '</script>'
# Show in new Window
HTML(s)
这里,df.to_HTML() 从包含大量换行符的数据框中创建一个 HTML 字符串。这些对 Javascript 来说是有问题的。 Javascript 中的多行字符串在 EOL 处需要 反斜杠,这就是为什么 python 必须使用 .replace() 方法修改 HTML 字符串的原因。
JavaScript 的 .innerHTML(而不是 document.write())真正酷的地方在于,您可以随时更新您的表格,而无需创建新窗口:
df /= 2
s = '<script type="text/Javascript">'
s += 'win.document.body.innerHTML = \'' + df.to_html().replace("\n",'\\') + '\';'
s += '</script>'
HTML(s)
这将立即对您打开的窗口中的桌子产生影响。
这里是R 为python 提供的View() 模拟器的简单建议:
def View(df):
css = """<style>
table { border-collapse: collapse; border: 3px solid #eee; }
table tr th:first-child { background-color: #eeeeee; color: #333; font-weight: bold }
table thead th { background-color: #eee; color: #000; }
tr, th, td { border: 1px solid #ccc; border-width: 1px 0 0 1px; border-collapse: collapse;
padding: 3px; font-family: monospace; font-size: 10px }</style>
"""
s = '<script type="text/Javascript">'
s += 'var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));'
s += 'win.document.body.innerHTML = \'' + (df.to_html() + css).replace("\n",'\\') + '\';'
s += '</script>'
return(HTML(s+css))
只需键入以下内容,即可在 jupyter 中使用:
View(df)
作为一种花哨的装饰,它还使用一些 CSS 为您打开的表格设置样式,使其看起来更好,并且可以与您从 RStudio 知道的内容相媲美。