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

如何将含列表的嵌套字典转换为指定格式的Pandas DataFrame?

解决方案

直接使用explode()会对所有列的列表进行笛卡尔积展开,不符合你需要的“单月份值非0,其余为0”的格式。可以通过单独处理每个月份列,再合并结果来实现需求:

步骤代码

import pandas as pd

# 原始数据
data = {123:  {'Feb': ['A', 'B'], 'Mar': ['A', 'B']}, 
        124: {'Feb': ['C'], 'Mar': ['A', 'B', 'C']}, 
        125: {'Feb': ['A', 'C'], 'Mar': ['A']} }

# 1. 转换为初始DataFrame,保留账号编号列
df = pd.DataFrame.from_dict(data, orient='index').rename_axis('账号编号').reset_index()

# 2. 逐个处理每个月份,生成对应数据块
processed_dfs = []
for target_month in ['Feb', 'Mar']:
    # 拆分当前月份的列表为单独行
    temp_df = df[['账号编号', target_month]].explode(target_month)
    # 其他月份列填充为0
    for col in ['Feb', 'Mar']:
        if col != target_month:
            temp_df[col] = '0'
    processed_dfs.append(temp_df)

# 3. 合并所有数据块,添加Jan列并调整列顺序
final_df = pd.concat(processed_dfs, ignore_index=True)
final_df['Jan'] = '0'
final_df = final_df[['账号编号', 'Jan', 'Feb', 'Mar']]

最终结果

账号编号JanFebMar
1230A0
1230B0
12300A
12300B
1240C0
12400A
12400B
12400C
1250A0
1250C0
12500A

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:32:18