How to show a pandas dataframe into a existing flask html table?

前端 未结 4 2023
暗喜
暗喜 2020-12-04 07:58

This may sound a noob question, but I\'m stuck with it as Python is not one of my best languages.

I have a html page with a table inside it, and I would like to show

4条回答
  •  死守一世寂寞
    2020-12-04 08:46

    working example:

    python code:

    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:

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

    or else use

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

    and remove {{titles[loop.index]}} line from html

    if you inspect element on html

    
        
        Title
    
    
    
    
                
    A B C
    0 0 5 a
    1 1 6 b
    2 2 7 c--
    3 3 8 d
    4 4 9 e

    as you can see it has tbody and thead with in table html. so you can easily apply css.

提交回复
热议问题