python - 将 pandas 数据框转换为嵌套字典

标签 python pandas dataframe dictionary

我有一个数据框,我想将其转换为嵌套字典。例如:

df=

<表类=“s-表”> <标题> ID 行动 负责 阶段 <正文> 1.1 索取文件 项目经理 1.0 创建文档请求 2.1 创建类(class)模块 作者 2.0 创建文档 2.2 发送模块以供审核 作者 2.0 创建文档 3.1 发布类(class) 审稿人 3.0发布文档 3.2 地址反馈 作者 3.0发布文档

最终,我需要将它变成一个嵌套字典,如下所示:

context = {'Section': 

[{'Phase': '1.0 Create Document',
   'Activity': [
            {'Responsible': 'Project Manager', 'ID': '1.1', 'Action': 'Request Document'},
            ],
        }, 
 {'Phase': '2.0 Create Document',
  'Activity': [
            {'Responsible': 'Writer', 'ID': '2.1', 'Action': 'Create course module'},
            {'Responsible': 'Writer', 'ID': '2.2', 'Action': 'Send module for review'},    
        ],
        },
{'Phase': '3.0 Publish Document',
  'Activity': [
            {'Responsible': 'Reviewers', 'ID': '3.1', 'Action': 'Publish course'},
            {'Responsible': 'Writer', 'ID': '3.2', 'Action': 'Address Feedback'},    
        ],
        }    
],
} 

我想过使用df.groupbyto_dict和一个 lambda功能,但我还没弄清楚如何让它工作

(抱歉,我知道这不是最干净的代码或示例;我仍在学习)

编辑:

我尝试过的代码是:

context = df.groupby('Phase')[['ID','Action','Responsible','Note','Output']].apply(lambda x: x.set_index('ID').to_dict(orient='index')).to_dict()

但这提供了错误的输出,因为它没有给出字典的正确键。正如我所想,我真正需要做的是在字典中创建嵌套列表,与正确的键匹配,按“阶段”分组

最佳答案

您可以在 groupby 中使用 to_dict,然后再次在结果上使用 to_dict 来获取嵌套记录:

data = (df.drop('Phase', axis=1) 
          .groupby(df['Phase'])
          .apply(lambda x: x.to_dict(orient='r'))
          .reset_index(name='Activity')
          .to_dict(orient='r'))

context = {'Section': data}
print(context)
{'Section': [{'Activity': [{'Action': 'Request Document',
                            'ID': 1.1,
                            'Responsible': 'Project Manager'}],
              'Phase': '1.0 Create Document Request'},
             {'Activity': [{'Action': 'Create course module',
                            'ID': 2.1,
                            'Responsible': 'Writer'},
                           {'Action': 'Send module for review',
                            'ID': 2.2,
                            'Responsible': 'Writer'}],
              'Phase': '2.0 Create Document'},
             {'Activity': [{'Action': 'Publish Course',
                            'ID': 3.1,
                            'Responsible': 'Reviewers'},
                           {'Action': 'Address feedback',
                            'ID': 3.2,
                            'Responsible': 'Writer'}],
              'Phase': '3.0 Publish Document'}]}

关于python - 将 pandas 数据框转换为嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69490653/

相关文章:

python - Django、Docker、Python - 无法在 python-alpine 上安装 Pillow

python - 级别 NaN 必须与名称相同

Python 和 C++ 集成。动态库问题

python - 将多个列字符串连接成一列

python - 如何使用包含列表值的列将多个 DataFrame 行合并为 1

python - 在 Tkinter 文本框中显示时,发出处理从串行端口读取的数据

python - 何时使用 SQLAlchemy 以及何时使用 Pandas 进行数据操作

python - 为什么seaborn会在面网格中一遍又一遍地渲染相同的图形?

python - 从数据框中选择事件出现前的最后 n 条记录

python - 如何限制 HDF5 上 pandas 查询的大小,使其不超过 RAM 限制?