我有一個像這樣的資料框,它是使用 app.py 中的以下函式創建的
cases deaths
state
New York 1203003648 31391997
California 2188008059 30864267
Texas 1745177048 28252336
Florida 1461739406 22255383
New Jersey 561292201 15263394
Pennsylvania 672001545 14669903
應用程式.py
def find_top_confirmed_states(n = 10):
df = pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv')
by_state = df.groupby('state').sum()[['cases', 'deaths']]
tcs = by_state.nlargest(n, 'deaths')
return tcs
tcs = find_top_confirmed_states()
@app.route('/')
def Index():
return render_template("index.html", table=tcs, cmap=html_map, list=tcs.values.tolist())
索引.html
{% for p in list %}
<tr>
<td>{{ p[0]}}</td>
<td>{{ p[1]}}</td>
<td>{{ p[2]}}</td>
</tr>
{% endfor %}
現在我只想在 html 中顯示這個表
我的桌子沒有顯示。我能做的最好的事情就是顯示病例數和死亡人數,但我無法讓各州顯示。如何使用將顯示在 html 表格中的資料框
uj5u.com熱心網友回復:
Pandas 有一個內置的DataFrame.to_html(). 您可以直接獲取該文本并將其嵌入您的網站。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html
uj5u.com熱心網友回復:
您可以使用
def Index():
return df.to_html(header="true", table_id="table")
要么
def Index():
return render_template('file.html', tables=[df.to_html(classes='data')], titles=df.columns.values
和html上述方法的 jinja 模板:
{% for table in tables %}
{{titles[loop.index]}}
{{ table|safe }}
{% endfor %}
也可以使用render_template和洗掉{{titles[loop.index]}}線
return render_template('file.html', tables=[df.to_html(classes='data', header="true")])
uj5u.com熱心網友回復:
我通過添加以下行解決了我的問題:
tcs2 = [(state, cases, deaths) for state, cases, deaths in zip(tcs.index, tcs['cases'],tcs['deaths'])]
這產生了以下輸出:
[('紐約', 1203003648, 31391997), ('加利福尼亞', 2188008059, 30864267), ('德克薩斯', 1745177048, 28252336),....]
所以我使用以下命令發送到我的 html 檔案:
@app.route('/')
def Index():
return render_template("index.html", table=tcs, cmap=html_map, tcs2=tcs2)
因此,我可以使用我已經擁有的代碼進行迭代以在我的 html 檔案中包含我的表:
{% for p in tcs2 %}
<tr>
<td>{{ p[0]}}</td>
<td>{{ p[1]}}</td>
<td>{{ p[2]}}</td>
</tr>
{% endfor %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439576.html
