user3605780
user3605780

Reputation: 7072

Iterate over pandas dataframe in jinja2

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.

I tried using to_dict(). But with

{% 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?

{% for key,value in x.items() %}
    <option value="{{ id }}">{{ text }}</option>
{% endfor %}

Upvotes: 26

Views: 29117

Answers (1)

user3605780
user3605780

Reputation: 7072

As John Galt suggested this works:

{% for index, row in x.iterrows() %}
      <option value="{{ row['id'] }}">{{ row['text'] }}</option>
{% endfor %}

Upvotes: 40

Related Questions