skip to Main Content

Unable to convert pandas header alone to html.
I have below code,

df = pd.read_csv("Employees.csv")
df1= df.columns.to_frame()
df1.to_html("upload.html")

Result of the code is ,

enter image description here

Expected result is,

enter image description here

Unable to get the header alone from the index of the data frame. Any suggestion would be appreciated.

3

Answers


  1. Chosen as BEST ANSWER

    Customised the code to generate html attributes. This is more efficient as we can also add CSS and other html properties.

    file = open("templates/upload.html", "w")
    table = ["""<table border="1"> n"""]
    file.writelines(table)
    file.close()
    
    file = open("templates/upload.html", "a")
    for row in list(df.columns):
        header = """<tr style="text-align: left;">n<th>""" + row + "</th>n</tr>n"
        file.writelines(header)
    file.close()
    
    file = open("templates/upload.html", "a")
    table = ["</table>"]
    file.writelines(table)
    file.close()
    

  2. You can set headers to false to get rid of the top row. And index to false to get rid of the first column.

    df1.to_html("upload.html", header=False, index=False)
    

    You’re left with the right column, which you can add styles to make it bold and centred like the left column.

    Documentation

    Hope this helps!

    Login or Signup to reply.
  3. Use df.head(0).to_html(header=True, index=False) to get just the headers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search