我有一个 python 脚本,它导入 CSV 文件,然后操作数据,然后使用 df.to_html 将其输出为 html。 我希望能够单击列标题来调用函数来对行进行排序。 我目前正在通过按下按钮进行排序。 我已添加到表中数据行的链接,但无法弄清楚如何让 df.to_html 添加标题的 onClick。
示例 html 是:
<table>
<th id="text" onClick="mySortFunction()">Column Heading</th>
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
Pandas 本身并不是为了添加这些功能而设计的。但是,您可以在
table_id
方法上使用 to_html()
属性,以便轻松识别 HTML 页面上的表。然后您可以使用数据表之类的库来为您添加排序和其他功能。
所以类似:
Python代码:
html_str = df.to_html(None, table_id="myPandasTableId")
html 文件:
<html>
<head>
<link rel="stylesheet" type= "text/css" href="https://cdn.datatables.net/2.1.4/css/dataTables.dataTables.min.css" />
</head>
<body>
<!-- pandas table goes here -->
<script type="text/javascript" src="https://cdn.datatables.net/2.1.4/js/dataTables.min.js"></script>
<script type="text/javascript">
let myDataTable = new DataTable('#myPandasTableId');
</script>
</body>
</html>