Export a pandas DataFrame into a HTML table

Overview:

  • A pandas DataFrame is a two-dimensional data container for processing voluminous data from various sources.
  • DataFrame can store objects of various Python types.
  • In Data Analytics it is a common requirement to publish final results such as a confusion matrix or a dashboard to an external format like excel, HTML, MySQL and others.
  • The method to_html() of the DataFrame class, returns a HTML string that represents a DataFrame object as a HTML table.

Example:

# Example Python program that exports a pandas DataFrame object

# into a HTML table

import pandas as pds

 

# A Python dictionary representing categories

categories = {"A": [1512, 1245, 1234],

              "B": [1547, 1598, 1345],

              "C": [1676, 1436, 1452]};

 

# Dictionary loaded into a pandas DataFrame             

dataFrame = pds.DataFrame(data=categories);

 

# Emit the DataFrame as a HTML string

html = dataFrame.to_html();

 

# Print the HTML

print(html);

 

Output:

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

  <thead>

    <tr style="text-align: right;">

      <th></th>

      <th>A</th>

      <th>B</th>

      <th>C</th>

    </tr>

  </thead>

  <tbody>

    <tr>

      <th>0</th>

      <td>1512</td>

      <td>1547</td>

      <td>1676</td>

    </tr>

    <tr>

      <th>1</th>

      <td>1245</td>

      <td>1598</td>

      <td>1436</td>

    </tr>

    <tr>

      <th>2</th>

      <td>1234</td>

      <td>1345</td>

      <td>1452</td>

    </tr>

  </tbody>

</table>

 

Output as seen in an Internet browser:

Converting a pandas DataFrame object into a HTMLTable

 


Copyright 2024 © pythontic.com