pandas - 如何使用 nbconvert 在 jupyter notebook 的 html 输出中添加垂直滚动条?

标签 pandas jupyter scrollbar nbconvert longtable

我正在使用 jupyter 自动化一些报告并将其导出到 html。我有一些大表,我想在表的右侧添加一个滚动条。这里有一个类似的问题:How to get a vertical scrollbar in HTML output from Jupyter notebooks .这是一个可重现的例子:

    import pandas as pd
    import numpy as np

    pd.set_option('display.max_columns', None)
    pd.set_option('display.max_rows', None)

    np.random.seed(2021)

    df = pd.DataFrame({'type': ['a'] * 50 + ['b'] * 50,
              'var_1': np.random.normal(size=100),
              'var_2': np.random.normal(size=100)})

我认为可以使用 .css 样式来完成,但我很难应用它。 Pandas 有一些有用的方法来设置表格样式 (https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html)。然后,我尝试了以下操作:

   vscrollbar = {
     'selector': 'div.output_html',
     'props': ' height: 500px; overflow-y: scroll;'
   }

   df.style.set_table_styles([vscrollbar])

之后,我使用 CLI 从 CLI 编译笔记本

   jupyter-nbconvert example.ipybn --to-html

输出不显示右滚动条。但是如果我检查 html 代码,我传递的 throw Pandas 样式就在那里

...
<style type="text/css">
#T_e24f1_ table {
  height: 500px;
  overflow-y: scroll;
}
</style>
<table id="T_e24f1_">
  <thead>
    <tr>
      <th class="blank level0">&nbsp;</th>
      <th class="col_heading level0 col0">type</th>
      <th class="col_heading level0 col1">var_1</th>
      <th class="col_heading level0 col2">var_2</th>
    </tr>
  </thead>
  <tbody>
...

我不知道我是否传递了正确的选择器,或者 jupyter 是否覆盖了这个样式。

如何在 jupyter nbconvert 的 html 输出中为长表获取正确的滚动条?

最佳答案

这里列出了您应该知道的事情。

  1. selector 是一种可以帮助您在 html 中选择一个或多个元素的方法。因此,也许您需要了解如何使用它。以你为例。它应该是 '',因为,如果您检查过 ipynb 中的代码输出是什么,您将看到如下所示。
#T_f2ffe_  div.output_html{
  height: 500px;
  overflow-y: scroll;
}

第一部分 #T_f2ffe_pandas 随机生成,第二部分 div.output_html 是您编写的内容。这些选择器一起工作,这将导致您不指定任何元素

  1. html中的一个table,它的高度是从td的高度和td的个数两方面来计算的。如果你想让css height起作用,你最好先添加display:inline-block

所以这是最终的答案,只需稍加改动即可。

vscrollbar = {
 'selector': '',
 'props': ' height: 500px; overflow-y: scroll;display: inline-block;'
}

df.style.set_table_styles([vscrollbar])

HTML 看起来像。

enter image description here

关于pandas - 如何使用 nbconvert 在 jupyter notebook 的 html 输出中添加垂直滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68628383/

相关文章:

python - 简单分组的奇怪结果

Python - pandas - 皮秒精度的时间序列数据

python - Jupyter 笔记本错误

vagrant - 无法通过本地浏览器访问本地 vagrant virtualbox 中的 jupyter notebook

html - 表格 HTML 溢出

python - Pandas 直方图 : plot histogram for each column as subplot of a big figure

python - Dataframe - 根据条件创建新列

python - 将导出的 .py 文件导入回 IPython Notebook

css - iFrame 上的水平和垂直滚动 - ie7

css - 如何用你自己的 css 覆盖 cloudmade maps css?