代码之家  ›  专栏  ›  技术社区  ›  Motta

如何将数据帧显示到现有的flask html表中?

  •  5
  • Motta  · 技术社区  · 6 年前

    这听起来可能是一个很难回答的问题,但我坚持认为Python不是我最好的语言之一。

    我有一个html页面,里面有一个表,我想在其中显示一个数据帧。 最好的方法是什么?使用pandasdataframe.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>
    
    2 回复  |  直到 6 年前
        1
  •  57
  •   Nihal Saranga    6 年前

    工作示例:

    python代码:

    from flask import Flask, request, render_template, session, redirect
    import numpy as np
    import pandas as pd
    
    
    app = Flask(__name__)
    
    df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                       'B': [5, 6, 7, 8, 9],
                       'C': ['a', 'b', 'c--', 'd', 'e']})
    
    
    @app.route('/', methods=("POST", "GET"))
    def html_table():
    
        return render_template('simple.html',  tables=[df.to_html(classes='data')], titles=df.columns.values)
    
    
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0')
    

    html格式:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    {% for table in tables %}
                {{titles[loop.index]}}
                {{ table|safe }}
    {% endfor %}
    </body>
    </html>
    

    或者使用

    return render_template('simple.html',  tables=[df.to_html(classes='data', header="true")])
    

    并移除 {{titles[loop.index]}} 来自html的行

    如果你检查html上的元素

    <html lang="en"><head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body style="">
    
    
                <table border="1" class="dataframe data">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>A</th>
          <th>B</th>
          <th>C</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>0</th>
          <td>0</td>
          <td>5</td>
          <td>a</td>
        </tr>
        <tr>
          <th>1</th>
          <td>1</td>
          <td>6</td>
          <td>b</td>
        </tr>
        <tr>
          <th>2</th>
          <td>2</td>
          <td>7</td>
          <td>c--</td>
        </tr>
        <tr>
          <th>3</th>
          <td>3</td>
          <td>8</td>
          <td>d</td>
        </tr>
        <tr>
          <th>4</th>
          <td>4</td>
          <td>9</td>
          <td>e</td>
        </tr>
      </tbody>
    </table>
    
    
    </body></html>

    如您所见,它在html表中有tbody和thead。所以你可以很容易地应用css。

        2
  •  30
  •   Chris Farr    5 年前

    以防有人觉得这有用。我选择了另一种方法,因为我需要更多的定制,包括在表中添加执行操作的按钮。我也真的不喜欢标准的表格格式,因为它是非常丑陋的IMHO。

    ...
    
    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>
    

    货物积载与系固安全操作规则

    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

        3
  •  10
  •   Chandu    6 年前
    # Declare table
    class SomeTable(Table):
        status = Col('Customer')
        city = Col('City')
        product_price = Col('Country')    
    
    # Convert the pandas Dataframe into dictionary structure
    output_dict = output.to_dict(orient='records')  
    
    # Populate the table
    table = SomeTable(output_dict)
    
    return (table.__html__())
    

    或者在返回静态HTML文件时,可以使用Flask将其呈现为页面

    @app.route('/<string:filename>/')
    def render_static(filename):
        return render_template('%s.html' % filename)
    

    这是我们如何在烧瓶里做的想法。希望你能理解这一点,让我知道如果它没有帮助!

    import pandas as pd
    
    df = pd.DataFrame({'col1': ['abc', 'def', 'tre'],
                       'col2': ['foo', 'bar', 'stuff']})
    
    
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return df.to_html(header="true", table_id="table")
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
    

    Output

    但是我更喜欢Flask的HTML特性,而不是DataFrame到HTML(由于样式的原因)

        4
  •  4
  •   Biarys    5 年前

    对我来说用Jinja的For循环

    {% for table in tables %}
                {{titles[loop.index]}}
                {{ table|safe }}
    {% endfor %}
    

    没有工作,因为它只是打印每个字符1 1。我只能用

    {{ table|safe }}
    
        5
  •  3
  •   mikelowry    4 年前

    APP.PY—应用程序工厂:

    ## YOUR DF LOGIC HERE 
    
    @app.route("/")
    def home():
        return render_template('index.html' column_names=df.columns.values, row_data=list(df.values.tolist()), zip=zip)
    
    

    静态模板(例如index.html)

     <table>
            <thead>
    
              <tr>
                {% for col in column_names %}
                <th>
                
                  {{col}}
                 
                </th>
                {% endfor %}
              </tr>
    
            </thead>
            <tbody>
              {% for row in row_data %}
              <tr>
                {% for col, row_ in zip(column_names, row) %}
                <td>{{row_}}</td>
                {% endfor %}
              </tr>
              {% endfor %}
    
             
            </tbody>
      
          </table>