【问题标题】:Pop-out / expand jupyter cell to new browser window弹出/展开jupyter单元到新的浏览器窗口
【发布时间】:2017-03-26 02:08:07
【问题描述】:

我有一个如下所示的 jupyter 笔记本单元:

有没有办法将它弹出/展开到新的浏览器窗口(看不到内联输出)?

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

【问题讨论】:

标签: python jupyter-notebook jupyter


【解决方案1】:

您可以使用 Javascript 打开一个新窗口,由 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 必须使用 .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)

这将立即对您打开的窗口中的桌子产生影响。

这里是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 为您打开的表格设置样式,使其看起来更好,并且可以与您从 RStudio 知道的内容相媲美。

【讨论】:

  • ?。对任何想要实现此功能的人的提示:确保您没有阻止 localhost 上的弹出窗口!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多