Movatterモバイル変換


[0]ホーム

URL:


How to Convert Pandas Dataframes to HTML Tables in Python

Learn how you can make interactive HTML tables with pagination, sorting and searching just from a pandas dataframe using pandas and jQuery data tables in Python.
  · 4 min read · Updated may 2024 ·General Python Tutorials

Ready to take Python coding to a new level? Explore ourPython Code Generator. The perfect tool to get your code up and running in no time. Start now!

There are many cases where you have to convert your Pandas dataframe into an HTML table. Two of the primary reasons are that you want to better view your dataset as a data analyst or integrate it into your organization's website.

In this tutorial, we will convert any Pandas dataframe into an interactive table with pagination, and we can sort by column and search.

To get started, of course, you have to have Pandas installed:

$ pip install pandas

Importing the necessary libraries:

import pandas as pdimport webbrowser

We'll be usingwebbrowser module to automatically open the resulting HTML table in a new tab on the default browser.

Let's make a function that accepts the dataframe as an argument and returns the HTML content for that:

def generate_html(dataframe: pd.DataFrame):    # get the table HTML from the dataframe    table_html = dataframe.to_html(table_id="table")    # construct the complete HTML with jQuery Data tables    # You can disable paging or enable y scrolling on lines 20 and 21 respectively    html = f"""    <html>    <header>        <link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet">    </header>    <body>    {table_html}    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>    <script type="text/javascript" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>    <script>        $(document).ready( function () {{            $('#table').DataTable({{                // paging: false,                    // scrollY: 400,            }});        }});    </script>    </body>    </html>    """    # return the html    return html

Luckily, Pandas has a built-into_html() method that generates the HTML content of that dataframe as atable tag. After that, we make a complete HTML page and add a jQuery data tables extension, so it's interactive.

By default, pagination, sorting by column, and searching are enabled; you can disable them if you want. For example, if you wish to disable pagination and show the entire dataframe, you can uncommentpaging: false (remember the commenting in Javascript is"//" and not"#" as in Python).

I'm grabbingthis dataset for demonstration purposes. Let's try it out:

if __name__ == "__main__":    # read the dataframe dataset    df = pd.read_csv("Churn_Modelling.csv")    # take only first 1000, otherwise it'll generate a large html file    df = df.iloc[:1000]    # generate the HTML from the dataframe    html = generate_html(df)    # write the HTML content to an HTML file    open("index.html", "w").write(html)    # open the new HTML file with the default browser    webbrowser.open("index.html")

After we get our HTML content, we write it into a newindex.html file and open it withwebbrowser.open() function. Here's what it looks like:

Resulting HTML TableThe cool thing is that we can search on the table:

Searching on the resulting HTML tableOr sort by a specific column:

Sort by column in the resulting HTML tableOr edit the pagination settings, for example showing 50 entries per page:

Editing Pagination settings on the resulting HTML tableYou can also see the pages below the table:

Editing pagination settings on the resulting HTML tableConclusion

Alright! That's it for the tutorial. I hope it's helpful for you to view your dataset better or integrate it as HTML content on your website.

If you want the other way around, extracting HTML tables and converting them to CSV files, then checkthis tutorial.

The dataset used in this tutorial is originally fromKaggle. You can get ithere if you don't have a Kaggle account.

Note that the styling of the table will only work if you have Internet connectivity. If you want it to work offline, you can simply download the JS/CSS files and put them in the current directory so it loads them from your local machine instead of from a CDN.

You can get the complete codehere.

Learn also:How to Extract Tables from PDF in Python

Happy coding ♥

Liked what you read? You'll love what you can learn from ourAI-powered Code Explainer. Check it out!

View Full Code Explain My Code
Sharing is caring!



Read Also


How to Extract Tables from PDF in Python
How to Convert HTML Tables into CSV Files in Python
How to Make a Network Usage Monitor in Python

Comment panel

    Got a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!





    Ethical Hacking with Python EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Ethical Hacking with Python EBook - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Practical Python PDF Processing Chapter.

    See how the book can help you build handy PDF Processing tools!



    [8]ページ先頭

    ©2009-2025 Movatter.jp