DataWiz
DataWiz

Reputation: 451

How do I loop over rows and columns of a pandas dataframe in jinja2?

I am just starting out with jinja2 and trying to generate lines of text from a dataframe. My template weather.txt looks like this:

{% for key, value in x.iterrows %}
    The day {{ df["date"] }} was {{ df["weather"] }}.
{% endfor %}

The dataframe weather looks something like this:

      date        weather
0  2017-03-31      warm
1  2017-04-21      cold
2  2017-07-01      rainy

Now I can't really figure out how to generate the desired output from this. When I use this code:

template = env.get_template("weather.txt")

output = template.render(x = weather)
print(output)

I get TypeError: 'method' object is not iterable

Upvotes: 1

Views: 3922

Answers (1)

sacuL
sacuL

Reputation: 51395

as the warning states, iterrows is a method, so you need to use parentheses:

{% for _, row in weather.iterrows() %}
    The day {{ row["date"] }} was {{ row["weather"] }}.
{% endfor %}

This should work assuming your dataframe is indeed called weather

Upvotes: 4

Related Questions