我能想到的最佳解决方案包括几个外部JS库:JQuery及其DataTables插件。这将使分页工作不仅仅需要很少的努力。
让我们设置一些HTML,JS和python:
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)
现在我们可以加载样本数据集进行测试:
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)
美丽的结果: 在此处输入图片说明
一些注意事项: