Pandas + Jinja: How to render a DataFrame as an HTML table

Updated: February 19, 2024 By: Guest Contributor Post a comment

Overview

In this tutorial, you will learn how to use Pandas and Jinja to render a DataFrame as an HTML table. Both tools are immensely powerful on their own – Pandas for data manipulation and analysis; Jinja for template rendering. When combined, they enable Python developers to dynamically create HTML tables that are both robust and responsive, paving the way for enhanced data presentation in web applications.

Getting started

First, make sure you have both Pandas and Jinja2 installed in your Python environment. If not, you can install them using pip:

pip install pandas jinja2

For demonstration, we’ll create a simple DataFrame:

import pandas as pd
data = { 'Name': ['John', 'Anna', 'Peter', 'Linda'],
        'Age': [28, 34, 29, 32],
        'City': ['New York', 'Paris', 'Berlin', 'London']}
df = pd.DataFrame(data)

Basic Rendering

The simplest way to render a DataFrame to an HTML table is by using the to_html() method provided by Pandas:

html_table = df.to_html()
print(html_table)

This will output a basic HTML table. However, it lacks styling and is not easily customizable.

Customizing with Jinja

To achieve a more styled and customizable table, we utilize Jinja. First, we need to create a Jinja template for our table:

{% raw %}<table>
    <thead>
        <tr>
            {% for column in df.columns %}
                <th>{{ column }}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        {% for row in df.itertuples() %}
            <tr>
                {% for cell in row[1:] %}
                    <td>{{ cell }}</td>
                {% endfor %}
            </tr>
        {% endfor %}
    </tbody>
</table>{% endraw %}

Next, create a Jinja environment and render the template with our DataFrame:

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('your_template_name.html')
html_table = template.render(df=df)
print(html_table)

This method allows for significant customization. You could add CSS directly within the template or link to an external stylesheet.

Advanced Techniques

Let’s elevate our table with additional Jinja features, such as conditional formatting and loop controls.

Conditional Formatting in Cells

Within the template, you can apply conditional formatting to highlight specific data points:

{% raw %}{% for row in df.itertuples() %}
    <tr>
        {% for cell in row[1:] %}
            {% if cell > 30 %}
                <td style="color: red;">{{ cell }}</td>
            {% else %}
                <td>{{ cell }}</td>
            {% endif %}
        {% endfor %}
    </tr>
{% endfor %}{% endraw %}

This simple condition applies a red color to any cell where the value is greater than 30, enabling quick visual identification of specific data ranges.

Including External CSS

For more comprehensive styling, it’s efficient to use an external CSS file. You can include it in your Jinja template as follows:

<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

This approach separates the structure from styling, making your HTML table more consistent and easier to maintain.

Conclusion

Combining Pandas and Jinja to render DataFrame as an HTML table not only enhances data presentation but also elevates the user experience through powerful customization options. The journey from basic to advanced usage sheds light on the tools’ flexibility and their ability to cater to various presentation needs. Implementing these techniques lays a solid foundation for presenting data-driven insights in a compelling manner.