You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用pandas set_table_styles设置表格宽度100%填满容器

Pandas表格样式设置:让表格填满容器的方法

背景

我有一个DataFrame,对其应用了多项样式设置后转换为HTML并在网页中展示。

当前使用的DataFrame及样式代码

th_props = [
  ('font-size', '14px'),
  ('text-align', 'left'),
  ('font-weight', 'bold'),
  ('color', '#6d6d6d'),
  ('background-color', '#eeeeef'),
  ('border','1px solid #eeeeef'),
  #('padding','12px 35px')
]

td_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
  #('width','100%')

]

cell_hover_props = [  # for row hover use <tr> instead of <td>
    ('background-color', '#eeeeef')
]

headers_props = [
    ('text-align','center'),
    ('font-size','1em')
]
#dict(selector='th:not(.index_name)',props=headers_props)

table_props = [
    ('width','100%')
]
#dict(selector='table',props=table_props),


styles = [
    dict(selector="th", props=th_props),
    dict(selector="td", props=td_props),
    dict(selector="td:hover",props=cell_hover_props),
    # dict(selector='th.col_heading',props=headers_props),
    dict(selector='th.col_heading.level0',props=headers_props),
    dict(selector='th.col_heading.level1',props=td_props),

]


arrays = [
    ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
    ["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=[None, "Brand"])

df = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index)

st.markdown(df.style.set_table_styles(styles).to_html(),unsafe_allow_html=True)

遇到的问题

在网页中渲染后,表格并未填满整个容器(表格未填满容器示意图)。

我尝试过在th_props和td_props中添加('width','100%'),代码如下:

td_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
  ('width','100%')
]

但得到的效果不符合预期(错误效果展示示意图)。

请问在pandas的set_table_styles中应该使用哪个选择器和属性,才能实现表格填满整个容器的效果(预期效果展示示意图)?

感谢解答!


内容的提问来源于stack exchange,提问作者Chronicles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:51:03