在 jinja2 中迭代 Pandas 数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40830975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate over pandas dataframe in jinja2
提问by user3605780
I have this dataframe:
我有这个数据框:
id text
0 12 boats
1 14 bicycle
2 15 car
Now I want to make a select dropdown in jinja2. But I cannot find a way to loop over the dataframe in jinja2.
现在我想在 jinja2 中做一个选择下拉菜单。但是我找不到在 jinja2 中循环数据帧的方法。
I tried using to_dict(). But with
我尝试使用 to_dict()。但是随着
{% for key,value in x.items() %}
it loops over id and text instead of the rows. How can I change this so I can do something like this in the template?
它遍历 id 和 text 而不是行。如何更改它以便我可以在模板中执行类似操作?
{% for key,value in x.items() %}
<option value="{{ id }}">{{ text }}</option>
{% endfor %}
回答by user3605780
As John Galt suggested this works:
正如约翰高尔特所建议的那样:
{% for key,value in x.iterrows() %}
<option value="{{ value['id'] }}">{{ value['text'] }}</option>
{% endfor %}