栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在pandas上分页dataframe.to_html()

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在pandas上分页dataframe.to_html()

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414535.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号