【问题标题】:How do I use a DataFrame to conditionally create documents using Jinja?如何使用 DataFrame 使用 Jinja 有条件地创建文档?
【发布时间】:2017-12-05 06:34:08
【问题描述】:

对于 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"
}

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

【问题讨论】:

    标签: python pandas jinja2


    【解决方案1】:

    我认为将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
    # }
    

    【讨论】:

    • 我已经这样做了,但是我遇到的问题是有条件地向模板添加值。例如,如果 df[nullable] 为真,则添加 null。
    • 在这种情况下,您必须像 {{ 'null' if row['nullable'] }} 那样在 Jinja 中实现它。我已经更新了我的答案。
    • TY 为您提供帮助
    • 您能帮我弄清楚如何将这些结果嵌套在父值下吗?假设我想将当前输出包装在一个新的父列下,该列可能有一些列,1-1 parent = child 或 1 to many parent to child1,..child n
    • 我认为 jinja 可能不是您想要的。您是否尝试过将“DataFrame”转换为 json?
    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    相关资源
    最近更新 更多