【问题标题】:Make to_html() mobile friendly or "Is it possible to add custom <td> tag attributes in to_html(...)?"使 to_html() 移动友好或“是否可以在 to_html(...) 中添加自定义 <td> 标记属性?”
【发布时间】:2021-08-05 05:10:51
【问题描述】:

我从一个数据框创建了一个表格的 html 渲染,我想让它对移动设备友好。我发现的一个解决方案需要为每个列条目添加属性到 &lt;td&gt; 标记(根据这个建议 https://codemyui.com/pure-css-responsive-table/ 使用决定何时从表格视图切换到一种列表视图的 CSS 文件)。

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

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>

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

【问题讨论】:

    标签: python html pandas mobile


    【解决方案1】:

    你可以做这样的事情(假设它只上升到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 中的数字更改为键的数量即可。

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2018-01-30
      • 1970-01-01
      相关资源
      最近更新 更多