弹出/展开 jupyter 单元格到新浏览器 window

Pop-out / expand jupyter cell to new browser window

我有一个 jupyter notebook 单元,看起来像这样:

有没有办法将其弹出/扩展到新浏览器window(看不到内联输出)?

基本上,我想从 R/RStudio 复制 View() 函数...这可能吗?

您可以使用 Javascript 打开一个新的 window,由 HTMLIPython.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 必须使用 [=17= 修改 HTML 字符串]方法。

JavaScript 的 .innerHTML(而不是 document.write())真正酷的地方在于,您可以随时更新 table,而无需创建新的window:

df /= 2
s  = '<script type="text/Javascript">'
s += 'win.document.body.innerHTML = \'' + df.to_html().replace("\n",'\') + '\';'
s += '</script>'
HTML(s)

这将对您在打开的 window 中的 table 立即生效。

这是 Rpython 提供的 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 为您打开的 table 设置样式,这样它看起来更漂亮并且与您从 RStudio 中了解到的相媲美。