TL, DR
If you ever tried to write a big table in HTML from scratch, you know how much it can be tedious. Fortunately, there are ways to convert data from a Pandas DataFrame to a HTML table with a simple call.
Making tables in HTML from Pandas DataFrames
HTML is the standard language of the web. Virtually all websites you see are rendered in HTML. Together with CSS and JavaScript, it builds the basic infrastructure of the web as we know it.
If you spent time more than once creating a table from scratch in HTML, you know it may be a terribly tedious process. And probably you dread going back and change that table, in case it needs to be updated.
Fortunately, other smart people had the same problem before and decided to do something about it. Amongst the large number of formats you can export data to in Pandas, you can also find HTML.
Creating your table
Let’s imagine you are handling your data in a Jupyter Notebook, and you want to export your results for inserting into your HTML page. Most probably, the object holding that data in a tabular format will be a Pandas DataFrame.
Then it’s your lucky day! All you need to do is to call one of the fantastic DataFrame methods:
import pandas as pd
df = pd.DataFrame({
"X": [10, 5, 7],
"Y": [21,15,9],
"p": [0.631, 0.557,0.364]
})
df.to_html()
The above command will return you a string with the Pandas DataFrame formatted as HTML Table and ready to be inserted in your HTML webpage. Specifically:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>X</th>
<th>Y</th>
<th>p</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>10</td>
<td>21</td>
<td>0.631</td>
</tr>
<tr>
<th>1</th>
<td>5</td>
<td>15</td>
<td>0.557</td>
</tr>
<tr>
<th>2</th>
<td>7</td>
<td>9</td>
<td>0.364</td>
</tr>
</tbody>
</table>
The code above will render as follow in your webpage:
X | Y | p | |
---|---|---|---|
0 | 10 | 21 | 0.631 |
1 | 5 | 15 | 0.557 |
2 | 7 | 9 | 0.364 |
There is a long set of parameters available to you in order to fine-tune the Latex table. Here I report some of the most useful:
columns
: the list of columns to export (by default, all of them)col_space
: the minimum width of each columnindex
: whether to write row names (by default True)notebook
: whether the table is for inserting in a Jupyter Notebook (by default False)classes
: string or list or tuple with CSS classes to be added in the generated HTML
Related links
- Pandas DataFrame.to_html() documentation link
Do you like our content? Check more of our posts in our blog!