Pandas Dataframe 在网页上的显示 [英] Pandas Dataframe display on a webpage
问题描述
我正在使用 Flask,但这可能适用于许多类似的框架.
I am using Flask but this probably applies to a lot of similar frameworks.
我构建了一个熊猫数据框,例如
I construct a pandas Dataframe, e.g.
@app.route('/analysis/<filename>')
def analysis(filename):
x = pd.DataFrame(np.random.randn(20, 5))
return render_template("analysis.html", name=filename, data=x)
模板 analysis.html 看起来像
The template analysis.html looks like
{% extends "base.html" %}
{% block content %}
<h1>{{name}}</h1>
{{data}}
{% endblock %}
这有效,但输出看起来很糟糕.它不使用换行符等.我玩过 data.to_html()
和 data.to_string()
显示框架的最简单方法是什么?
This works but the output looks horrible. It doesn't use linebreaks etc.
I have played with data.to_html()
and data.to_string()
What's the easiest way to display a frame?
推荐答案
以下应该有效:
@app.route('/analysis/<filename>')
def analysis(filename):
x = pd.DataFrame(np.random.randn(20, 5))
return render_template("analysis.html", name=filename, data=x.to_html())
# ^^^^^^^^^
检查文档其他选项,如 CSS 样式.
Check the documentation for additional options like CSS styling.
此外,您需要像这样调整模板:
Additionally, you need to adjust your template like so:
{% extends "base.html" %}
{% block content %}
<h1>{{name}}</h1>
{{data | safe}}
{% endblock %}
为了告诉 Jinja 您正在传递标记.感谢 @SeanVieira 的提示.
in order to tell Jinja you're passing in markup. Thanks to @SeanVieira for the tip.
这篇关于Pandas Dataframe 在网页上的显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!