【问题标题】:Inserting HTML table into page after converting pandas dataframe转换熊猫数据框后将HTML表格插入页面
【发布时间】:2020-03-23 01:49:15
【问题描述】:

我试图在我的烧瓶应用程序中的页面上显示一个 HTML 表格,从 pandas 数据框转换它。该应用程序首先从“主页”页面上的下拉菜单中获取三个变量,然后根据这些变量创建一个数据框(网络根据选择从 URL 中抓取某些数据)。

然后,一旦单击主页上的提交按钮(这也会更改页面),我就会将 df 保存为 pickle 文件,以便可以将其打开并转换为另一个页面上的 HTML 表格...

下面是我的 show_results 方法,它在其中调用 fetch results(这是数据帧被腌制的地方),然后在尝试添加表之前返回模板:

def show_results():
    fetch_results()
    return render_template("get_results.html")
    cache_dir = os.path.join(ROOT_PATH, "cache")
    cache_file = os.path.join(cache_dir, "file.p")
    if request.method == "POST":
        with open(cache_file, "rb") as fid:
            results = pickle.load(fid)
        results_table = results.to_html()
    print(results_table)

我的总体想法是返回模板,然后将表格添加到其中...

目前,get_results.html 只有一个导航栏和一个标题。我尝试按照 GeeksForGeeks 教程进行操作:

https://www.geeksforgeeks.org/python-pandas-dataframe-to_html-method/

任何指针?

【问题讨论】:

    标签: python pandas dataframe pickle


    【解决方案1】:

    您可以将数据框作为表格传递给模板 html,例如:

    @app.route('/dropDownVals', methods=['GET' ,'POST'])
    def getDropDownVals():
        conn = sqlite3.connect("Casa.db")
        df = pd.read_sql_query("""SELECT * FROM(
        SELECT DISTINCT TEAMA FROM [TABLE]
    
        UNION 
    
        SELECT DISTINCT TEAMB FROM [TABLE]
        ) AS X
        WHERE TEAMA NOT LIKE '%#%'
        ORDER BY 1""", conn)
        c = conn.cursor()
        conn.commit()  # commit needed
        c.close()
        return render_template('findCollisions.html', tables=[df.to_html(classes='data', header="true")], titles=df.columns.values)
    

    然后在模板页面上,您可以使用 Jinja 模板获取这些值:

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

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 2017-08-26
      • 2019-06-05
      • 1970-01-01
      • 2021-10-27
      • 2018-08-25
      • 2017-08-27
      • 1970-01-01
      相关资源
      最近更新 更多