我有一个数据框,我想将其转换为嵌套字典。例如:
df=
最终,我需要将它变成一个嵌套字典,如下所示:
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.groupby
和to_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/