Convert Pandas DataFrame to HTML Table – Python

To convert Pandas DataFrame to HTML table:

html_table = df.to_html()
print(html_table)

To justify the column labels to the left:

html_table = df.to_html(justify='left')
print(html_table)

To remove the index labels and justify the column labels to the left:

html_table = df.to_html(index=False, justify='left')
print(html_table)

Example of Converting Pandas DataFrame to HTML Table

First, create a DataFrame as follows:

import pandas as pd

data = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
        'price': [1200, 200, 400, 300, 150]
        }

df = pd.DataFrame(data)
print(df)

Here is the DataFrame that you’ll get:

  product_name  price
0       laptop   1200
1      printer    200
2       tablet    400
3         desk    300
4        chair    150

Next, convert the DataFrame to HTML table as captured below:

import pandas as pd

data = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
        'price': [1200, 200, 400, 300, 150]
        }

df = pd.DataFrame(data)

html_table = df.to_html(index=False, justify='left')
print(html_table)

As you can see, the DataFrame was converted to HTML table:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: left;">
      <th>product_name</th>
      <th>price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>laptop</td>
      <td>1200</td>
    </tr>
    <tr>
      <td>printer</td>
      <td>200</td>
    </tr>
    <tr>
      <td>tablet</td>
      <td>400</td>
    </tr>
    <tr>
      <td>desk</td>
      <td>300</td>
    </tr>
    <tr>
      <td>chair</td>
      <td>150</td>
    </tr>
  </tbody>
</table>

For additional options that you may apply, please visit the Pandas Documentation.