我能想到的最佳解决方案涉及一对外部JS库:JQuery及其DataTables plugin。这样做可以远远超过分页,只需很少的努力。
让我们设置一些HTML,JS和Python:
from tempfile import NamedTemporaryFile
import webbrowser
base_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笔记本中测试过,但也应该在普通Python中工作。
您可以跳过df_window并将返回的值从df_html写入HTML文件。