pandas to_html: add attributes to table tag

时间:2017-04-09 23:28:13

标签: python html pandas

I'm using the pandas to_html() method to build a table for my website. I want to add some attributes to the <table> tag; however I'm not sure how to do this.

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

Which produces:

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

I want to produce the following:

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

1 个答案:

答案 0 :(得分:2)

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">