使 to_html() 适合移动设备或 "Is it possible to add custom <td> tag attributes in to_html(...)?"

Make to_html() mobile friendly or "Is it possible to add custom <td> tag attributes in to_html(...)?"

我从数据帧创建了 html 渲染 table,我想让它适合移动设备。我发现的一种解决方案需要为每个列条目的 <td> 标签添加属性(根据此建议 https://codemyui.com/pure-css-responsive-table/ 使用 CSS 文件决定何时从 table 切换查看一种列表视图)。

所以基本上我想得到这个代码

import pandas as pd

df = pd.DataFrame({'H1': [1,2], 'H2':[10,20]})
print(df.to_html())                  

制作这样的东西:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>a</th>
      <th>b</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td data-column="H1">1</td>
      <td data-column="H2">10</td>
    </tr>
    <tr>
      <th>1</th>
      <td data-column="H1">2</td>
      <td data-column="H2">20</td>
    </tr>
  </tbody>
</table>

如果这不是要走的路,我很乐意听到任何建议。

你可以这样做(假设它只达到 h2):

tab_html = df.to_html()

ntd = tab_html.count("<td>")
tab_html = tab_html.replace('<td>', '<td data-column="H{}">')
colindex = [i%2 + 1 for i in range(ntd)]
print(tab_html.format(*colindex))

只要 h1h2 的长度相同并且 {} 没有出现在您的 html 中的其他地方,这将有效。如果你想增加键的数量(比如最多 h4),只需将 i%2 中的数字更改为键的数量。