I have a dataframe like this which I created using the function below in 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
app.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())
index.html
{% for p in list %}
<tr>
<td>{{ p[0]}}</td>
<td>{{ p[1]}}</td>
<td>{{ p[2]}}</td>
</tr>
{% endfor %}
Now I just want to show this table in html
My table is not showing. The best that I could do was to show the number of cases and death, but I can't make the states to show. How do I work with this dataframe that will show in a table in html
CodePudding user response:
Pandas has a built-in DataFrame.to_html()
. You can take that text directly and embed it in your website.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html
CodePudding user response:
You can use
def Index():
return df.to_html(header="true", table_id="table")
or
def Index():
return render_template('file.html', tables=[df.to_html(classes='data')], titles=df.columns.values
and html
jinja template for above method:
{% for table in tables %}
{{titles[loop.index]}}
{{ table|safe }}
{% endfor %}
also is possible to use render_template
and remove {{titles[loop.index]}}
line
return render_template('file.html', tables=[df.to_html(classes='data', header="true")])
CodePudding user response:
I solved my problem by adding the following line:
tcs2 = [(state, cases, deaths) for state, cases, deaths in zip(tcs.index, tcs['cases'],tcs['deaths'])]
this generated the following output:
[('New York', 1203003648, 31391997), ('California', 2188008059, 30864267), ('Texas', 1745177048, 28252336),....]
so I sent to my html file using:
@app.route('/')
def Index():
return render_template("index.html", table=tcs, cmap=html_map, tcs2=tcs2)
So I could just iterate to have my table in my html file using the code that I already had which was:
{% for p in tcs2 %}
<tr>
<td>{{ p[0]}}</td>
<td>{{ p[1]}}</td>
<td>{{ p[2]}}</td>
</tr>
{% endfor %}