【问题标题】:pandas to_html: add attributes to table tagpandas to_html:向表格标签添加属性
【发布时间】:2017-09-04 21:31:22
【问题描述】:

我正在使用 pandas to_html() 方法为我的网站构建表格。我想为<table> 标签添加一些属性;但是我不知道该怎么做。

my_table = Markup(df.to_html(classes="table"))

产生:

<table border="1" class="dataframe table">

我想制作以下内容:

<table border="1" class="dataframe table" attribute="value" attribute2="value2">

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    这可以通过使用简单的正则表达式操作呈现的 html 来实现:

    import re
    
    df = pd.DataFrame(1, index=[1, 2], columns=list('AB'))
    
    html = df.to_html(classes="table")
    html = re.sub(
        r'<table([^>]*)>',
        r'<table\1 attribute="value" attribute2="value2">',
        html
    )
    
    print(html.split('\n')[0])
    
    <table border="1" class="dataframe table" attribute="value" attribute2="value2">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-08
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多