Pagination on pandas dataframe.to_html ()

I have a huge pandas dataframe, which I convert to an html table dataframe.to_html() , its about 1000 lines. Any easy way to use pagination so that I don't have to scroll through all 1000 lines. Say look at the first 50 lines, then click next to the next 50 lines?

+6
source share
1 answer

The best solution I can think of includes a couple of external JS libraries: JQuery and the DataTables Plugin . This will allow much more than pagination, with minimal effort.

Let some HTML, JS and python be configured:

 from tempfile import NamedTemporaryFile import webbrowser base_html = """ <!doctype html> <html><head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css"> <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script> </head><body>%s<script type="text/javascript">$(document).ready(function(){$('table').DataTable({ "pageLength": 50 });});</script> </body></html> """ def df_html(df): """HTML table with pagination and other goodies""" df_html = df.to_html() return base_html % df_html def df_window(df): """Open dataframe in browser window using a temporary file""" with NamedTemporaryFile(delete=False, suffix='.html') as f: f.write(df_html(df)) webbrowser.open(f.name) 

And now we can download the sample data for testing it:

 from sklearn.datasets import load_iris import pandas as pd iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df_window(df) 

Great result: enter image description here

A few notes:

  • Note the pageLength parameter in the base_html line. Here I determined the default number of lines per page. You can find other optional parameters on the DataTable parameter page.
  • The df_window function df_window been tested on a Jupyter Notebook, but should also work on plain python.
  • You can skip df_window and just write the return value from df_html to the HTML file.
0
source

All Articles