为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地10843 2021-06-28 18:19:33
这听起来可能是个菜鸟问题,但我坚持下去,因为 Python 不是我最好的语言之一。我有一个 html 页面,里面有一个表格,我想在其中显示一个 Pandas 数据框。最好的方法是什么?使用pandasdataframe.to_html?pyfrom 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>
查看完整描述

3 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

如果有人觉得这有帮助。我选择了一个替代方案,因为我需要更多的自定义,包括在表中添加执行操作的按钮的能力。我也真的不喜欢标准表格格式,因为恕我直言,它非常难看。


...


df = pd.DataFrame({'Patient Name': ["Some name", "Another name"],

                       "Patient ID": [123, 456],

                       "Misc Data Point": [8, 53]})

...


# link_column is the column that I want to add a button to

return render_template("patient_list.html", column_names=df.columns.values, row_data=list(df.values.tolist()),

                           link_column="Patient ID", zip=zip)

HTML 代码:这将任何 DF 动态转换为可定制的 HTML 表


<table>

    <tr>

        {% for col in column_names %}

        <th>{{col}}</th>

        {% endfor %}

    </tr>

    {% for row in row_data %}

    <tr>

        {% for col, row_ in zip(column_names, row) %}

        {% if col == link_column %}

        <td>

            <button type="submit" value={{ row_ }} name="person_id" form="patient_form" class="patient_button">

                {{ row_ }}

            </button>

        </td>

        {% else %}

        <td>{{row_}}</td>

        {% endif %}

        {% endfor %}

    </tr>

    {% endfor %}


</table>

CSS 代码


table {

    font-family: arial, sans-serif;

    border-collapse: collapse;

    width: 100%;

}


td, th {

    border: 1px solid #dddddd;

    text-align: left;

    padding: 8px;

}


tr:nth-child(even) {

    background-color: #dddddd;

}

它表现得非常好,看起来比.to_html输出好得多。


查看完整回答
反对 回复 2021-07-06
  • 3 回答
  • 0 关注
  • 291 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号