How to render Pandas DataFrame as HTML Table?

How to render Pandas DataFrame as HTML Table?

Pandas has built-in support to render a DataFrame as an HTML table. Here's how you can do that:

  • Using the to_html method: This method returns the DataFrame as an HTML table. You can then display this table in a Jupyter notebook, save it to an HTML file, or embed it within a larger HTML document.
import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) # Convert DataFrame to HTML html_table = df.to_html() # If you want to save the HTML to a file: with open("output.html", "w") as file: file.write(html_table) 
  • Displaying in a Jupyter Notebook: If you are working in a Jupyter notebook, DataFrames will be automatically rendered as tables when they are the last expression in a cell.

However, if you want to explicitly convert and display as HTML, you can use the display function and HTML class from the IPython.display module:

from IPython.display import display, HTML # Display the DataFrame as an HTML table display(HTML(df.to_html())) 
  • Styling the DataFrame: Pandas also provides the style property to generate a Styler object, which allows you to set specific styling to the table. Once you've set your styles, you can use the render method to convert it to HTML.
styled = df.style.set_table_attributes("border=1").set_caption('Sample DataFrame') html_table = styled.render() # Save or display the styled table as desired 

With these approaches, you can render a Pandas DataFrame as an HTML table either for display within Jupyter or for inclusion in an HTML document.


More Tags

elementwise-operations java-me oracle-apps ecmascript-next selenium-ide angularfire2 titlebar soap-client zoneddatetime jsonparser

More Programming Guides

Other Guides

More Programming Examples