如何使用DataFrame使用Jinja有条件地创建文档?

时间:2017-12-05 06:34:08

标签: python pandas jinja2

对于DataFrame中的每一行,我想打印出avro架构的一些值。我有一个看起来像这样的DataFrame。

import pandas as pd

x = pd.DataFrame({'column' : ['id','type','time']
    , 'desc': ['the sk',' the type' , 'epoch time']
    ,'nullable':[False, False, True]})

print x

对于DataFrame中的每一行,我想为Jinja模板创建输入

所以我的输出看起来像是:

{
name       : "id"
description: "the sk"
}
{
name       :"type"
description:"the type"
}
{
name       :"time","null"
description:"epoch time"
}

我该怎么做?我还希望根据我的数据框中的其他列值有条件地嵌套结果。

1 个答案:

答案 0 :(得分:0)

我认为将DataFrame转换为dict是解决方案。我使用orient='records'来获得适合渲染的dict

from jinja2 import Template

# Template definition
template = Template("""{% for row in data %}
{
name:  {{ row['column'] }}{{ ', null' if row['nullable'] }}
description: {{ row['desc'] }}
}
{% endfor %}""")

# Rendering
print(template.render(name='John Doe', data=x.to_dict(orient='records')))

# {
# name:  id
# description: the sk
# }
# 
# {
# name:  type
# description:  the type
# }
#
# {
# name:  time, null
# description: epoch time
# }