6
我有一个庞大的熊猫数据框我正在转换为html表格,即dataframe.to_html()
,它的大约1000行。任何简单的方法来使用分页,以便我不必滚动整个1000行。说,查看前50行,然后点击下一行以查看后续50行?关于熊猫分页dataframe.to_html()
我有一个庞大的熊猫数据框我正在转换为html表格,即dataframe.to_html()
,它的大约1000行。任何简单的方法来使用分页,以便我不必滚动整个1000行。说,查看前50行,然后点击下一行以查看后续50行?关于熊猫分页dataframe.to_html()
我能想到的最佳解决方案涉及一对外部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笔记本中测试过,但也应该在普通Python中工作。df_window
并将返回的值从df_html
写入HTML文件。
这确实是一个相当困难的问题!如果可以使用CSS类实现“分页”,则可以尝试有条件地使用[Style](http://pandas.pydata.org/pandas-docs/stable/style.html)(即0-49行 - 样式:第1页,第50-99页 - 样式:第2页等)。 – MaxU
您是否想要在Jupyter笔记本中查看它,或者将它作为独立的HTML文件进行查看? – Shovalt