我能想到的最佳解决方案涉及几个外部 JS 库:JQuery 及其DataTables plugin。这将允许的不仅仅是分页,而且只需很少的努力。
让我们设置一些 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)
美丽的结果:
几点说明:
- 注意
base_html 字符串中的pageLength 参数。这是我定义每页默认行数的地方。您可以在 DataTable options page 中找到其他可选参数。
-
df_window 函数在 Jupyter Notebook 中进行了测试,但在普通 python 中也应该可以工作。
- 您可以跳过
df_window,只需将df_html 的返回值写入HTML 文件。
编辑:如何通过远程会话(例如 Colab)进行这项工作
在远程笔记本上工作时,例如在 Colab 或 Kaggle 中,临时文件方法将不起作用,因为文件保存在远程计算机上,您的浏览器无法访问。一种解决方法是下载构建的 HTML 并在本地打开它(添加到前面的代码):
import base64
from IPython.core.display import display, HTML
my_html = df_html(df)
my_html_base64 = base64.b64encode(my_html.encode()).decode('utf-8')
display(HTML(f'<a download href="data:text/html;base64,{my_html_base64}" target="_blank">Download HTML</a>'))
这将产生一个包含整个 HTML 编码为 base64 字符串的链接。点击它会下载HTML文件,然后您可以直接打开它并查看表格。