如何将 Pandas 数据框显示到现有的 Flask html 表中?

这听起来可能是个菜鸟问题,但我坚持下去,因为 Python 不是我最好的语言之一。


我有一个 html 页面,里面有一个表格,我想在其中显示一个 Pandas 数据框。最好的方法是什么?使用pandasdataframe.to_html?


py


from flask import Flask;

import pandas as pd;

from pandas import DataFrame, read_csv;


file = r'C:\Users\myuser\Desktop\Test.csv'

df = pd.read_csv(file)

df.to_html(header="true", table_id="table")

html


<div class="table_entrances" style="overflow-x: auto;">


  <table id="table">


    <thead></thead> 

    <tr></tr>


  </table>


</div>


慕的地10843
浏览 292回答 3
3回答

慕后森

如果有人觉得这有帮助。我选择了一个替代方案,因为我需要更多的自定义,包括在表中添加执行操作的按钮的能力。我也真的不喜欢标准表格格式,因为恕我直言,它非常难看。...df = pd.DataFrame({'Patient Name': ["Some name", "Another name"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Patient ID": [123, 456],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Misc Data Point": [8, 53]})...# link_column is the column that I want to add a button toreturn render_template("patient_list.html", column_names=df.columns.values, row_data=list(df.values.tolist()),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;link_column="Patient ID", zip=zip)HTML 代码:这将任何 DF 动态转换为可定制的 HTML 表<table>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; {% for col in column_names %}&nbsp; &nbsp; &nbsp; &nbsp; <th>{{col}}</th>&nbsp; &nbsp; &nbsp; &nbsp; {% endfor %}&nbsp; &nbsp; </tr>&nbsp; &nbsp; {% for row in row_data %}&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; {% for col, row_ in zip(column_names, row) %}&nbsp; &nbsp; &nbsp; &nbsp; {% if col == link_column %}&nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" value={{ row_ }} name="person_id" form="patient_form" class="patient_button">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{ row_ }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; {% else %}&nbsp; &nbsp; &nbsp; &nbsp; <td>{{row_}}</td>&nbsp; &nbsp; &nbsp; &nbsp; {% endif %}&nbsp; &nbsp; &nbsp; &nbsp; {% endfor %}&nbsp; &nbsp; </tr>&nbsp; &nbsp; {% endfor %}</table>CSS 代码table {&nbsp; &nbsp; font-family: arial, sans-serif;&nbsp; &nbsp; border-collapse: collapse;&nbsp; &nbsp; width: 100%;}td, th {&nbsp; &nbsp; border: 1px solid #dddddd;&nbsp; &nbsp; text-align: left;&nbsp; &nbsp; padding: 8px;}tr:nth-child(even) {&nbsp; &nbsp; background-color: #dddddd;}它表现得非常好,看起来比.to_html输出好得多。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python