Sling Academy
Home/Pandas/Pandas + Jinja: How to render a DataFrame as an HTML table

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

Last updated: February 19, 2024

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.

Next Article: Pandas + FastAPI: How to serve a DataFrame as a REST API (with pagination)

Previous Article: Pandas: How to save a DataFrame in JSON format (3 examples)

Series: DateFrames in Pandas

Pandas

You May Also Like

  • How to Use Pandas Profiling for Data Analysis (4 examples)
  • How to Handle Large Datasets with Pandas and Dask (4 examples)
  • Pandas – Using DataFrame.pivot() method (3 examples)
  • Pandas: How to ‘FULL JOIN’ 2 DataFrames (3 examples)
  • Pandas: Select columns whose names start/end with a specific string (4 examples)
  • 3 ways to turn off future warnings in Pandas
  • How to Integrate Pandas with Apache Spark
  • How to Use Pandas for Web Scraping and Saving Data (2 examples)
  • How to Clean and Preprocess Text Data with Pandas (3 examples)
  • Pandas – Using Series.replace() method (3 examples)
  • Pandas json_normalize() function: Explained with examples
  • Pandas: Reading CSV and Excel files from AWS S3 (4 examples)
  • Using pandas.Series.rank() method (4 examples)
  • Pandas: Dropping columns whose names contain a specific string (4 examples)
  • Pandas: How to print a DataFrame without index (3 ways)
  • Fixing Pandas NameError: name ‘df’ is not defined
  • Pandas – Using DataFrame idxmax() and idxmin() methods (4 examples)
  • Pandas FutureWarning: ‘M’ is deprecated and will be removed in a future version, please use ‘ME’ instead
  • Pandas: Checking equality of 2 DataFrames (element-wise)