我能想到的最佳解决方案包括几个外部JS库:JQuery及其DataTables插件。这将使分页工作不仅仅需要很少的努力。
让我们设置一些HTML,JS和python:
from tempfile import NamedTemporaryFileimport webbrowserbase_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_htmldef 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)现在我们可以加载样本数据集进行测试:
from sklearn.datasets import load_irisimport pandas as pdiris = load_iris()df = pd.Dataframe(iris.data, columns=iris.feature_names)df_window(df)
美丽的结果: 在此处输入图片说明
一些注意事项:
- 注意字符串中的
pageLength
参数base_html。这是我定义每页默认行数的地方。您可以在DataTable选项页中找到其他可选参数。 - 该df_window功能已在
Jupyter Notebook
中进行了测试,但也应在纯Python中工作。 - 您可以跳过
df_window
并将返回的值直接写入df_htmlHTML文件。



