簡體   English   中英

如何使用DataFrame使用Jinja有條件地創建文檔?

[英]How do I use a DataFrame to conditionally create documents using Jinja?

對於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"
}

我怎樣才能做到這一點? 我還想根據數據框中的其他列值有條件地嵌套結果。

我認為將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
# }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM