You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将pandas dataframe按Phase分组转换为指定嵌套字典结构

pandas转换为指定结构嵌套字典的实现方法

你之前的代码问题在于分组后生成的是ID为键的字典结构,不符合Activity需要的记录列表要求,调整后代码如下:

完整实现代码

import pandas as pd

# 构造示例数据,实际使用时替换为你自己的DataFrame即可
df = pd.DataFrame({
    'ID': ['1.1', '2.1', '2.2', '3.1', '3.2'],
    'Action': ['Request Document', 'Create course module', 'Send module for review', 'Publish Course', 'Address feedback'],
    'Responsible': ['Project Manager', 'Writer', 'Writer', 'Reviewers', 'Writer'],
    'Phase': ['1.0 Create Document Request', '2.0 Create Document', '2.0 Create Document', '3.0 Publish Document', '3.0 Publish Document']
})

# 核心转换逻辑
context = {
    'Section': [
        {
            'Phase': phase,
            # 如果需要加入Note、Output等其他字段,在下面的列表中补充列名即可
            'Activity': group[['ID', 'Action', 'Responsible']].to_dict(orient='records')
        }
        # sort=False参数保留Phase在原数据中出现的顺序,不需要可删除
        for phase, group in df.groupby('Phase', sort=False)
    ]
}

可选调试写法

如果习惯用循环写法更易调试,也可以用如下等价代码:

section_list = []
for phase, group in df.groupby('Phase', sort=False):
    activity_list = group[['ID', 'Action', 'Responsible']].to_dict(orient='records')
    section_list.append({'Phase': phase, 'Activity': activity_list})
context = {'Section': section_list}

打印context即可得到你要求的完全匹配的嵌套结构。

内容的提问来源于stack exchange,提问作者Amoakk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:15:03