【问题标题】:Pandas to nested YAML熊猫到嵌套 YAML
【发布时间】:2022-01-20 10:53:54
【问题描述】:

我正在尝试构建 yaml 内容并将其转储到文件中:

它应该是这样的

group:
  Base Configuration:
    id: 1
    group_name: Base Configuration
    group_members:
    - S3-WLP-Kafka-topics-test
    - S3-WLP-BATCH-API-503-P
    group_description: Lorem Ipsum is simply dummy text
  Entity Persistence:
    id: 2
    group_name: Entity Persistence
    group_members:
    - Entity-INPUT-DATA-PERSISTENCE
    - Entity-OUTPUT-DATA-PERSISTENCE
    group_description: Lorem Ipsum is not simply random text.
  API TESTS:
    id: 3
    group_name: API TESTS
    group_members:
    - API Configuration
    group_description: Standard chunk of Lorem Ipsum

我的 pandas 数据框如下所示:

id group_name group_members group_description level
1 Base Configuration ['S3-WLP-Kafka-topics-test', 'S3-WLP-BATCH-API-503-P'] Lorem Ipsum is simply dummy text group
2 Entity Persistence ['Entity-INPUT-DATA-PERSISTENCE', 'Entity-OUTPUT-DATA-PERSISTENCE'] Lorem Ipsum is not simply random text. group
3 API TESTS ['API Configuration'] Standard chunk of Lorem Ipsum group

这是我实现这一目标的尝试。

        x = self.df_merged['level'].tolist()
        y = self.df_merged['group_name'].tolist()
        z = self.df_merged['id'].tolist()
        a = self.df_merged['group_description'].tolist()
        self.df_merged = self.df_merged.set_index(['level', 'group_name', 'id', 'group_description'])
        self.df_merged = self.df_merged.reindex(pd.MultiIndex.from_tuples(zip(x, y, z, a)))
        nested_dict = collections.defaultdict(dict)
        for keys, value in self.df_merged.group_members.iteritems():
            nested_dict[keys[0]][keys[1]] = value

这给了我:

defaultdict(<class 'dict'>, {'group': {'Base Configuration': ['S3-WLP-Kafka-topics-test', 'S3-WLP-BATCH-API-503-P'], 'Entity Persistence': ['Entity-INPUT-DATA-PERSISTENCE', 'Entity-OUTPUT-DATA-PERSISTENCE'], 'API TESTS': ['API Configuration']}})

虽然这不是我想要的,我的尝试也没有成功

【问题讨论】:

    标签: python pandas dictionary multi-index


    【解决方案1】:

    如果其他人也在寻找相同的东西,我终于用groupby()to_dict()实现了它

    data = self.df_unchanged.groupby('level')[['group_name', 'id', 'group_description', 'group_members']].apply(
                lambda x: x.set_index('group_name').to_dict(orient='index')).to_dict()
    

    最后转储到 yaml 文件:

        with open("test.yaml", "w") as yaml_file:
            yaml_file.write(yaml.dump(data, allow_unicode=True, default_flow_style=False, sort_keys=False))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 2018-05-05
      • 2014-08-13
      • 2019-03-12
      • 2018-08-13
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多