您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在pandas上分页dataframe.to_html()

在pandas上分页dataframe.to_html()

我能想到的最佳解决方包括几个外部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)

美丽的结果: 在此处输入图片说明

一些注意事项:

其他 2022/1/1 18:42:07 有393人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶