如何将含列表的嵌套字典转换为指定格式的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']]
最终结果
| 账号编号 | Jan | Feb | Mar |
|---|---|---|---|
| 123 | 0 | A | 0 |
| 123 | 0 | B | 0 |
| 123 | 0 | 0 | A |
| 123 | 0 | 0 | B |
| 124 | 0 | C | 0 |
| 124 | 0 | 0 | A |
| 124 | 0 | 0 | B |
| 124 | 0 | 0 | C |
| 125 | 0 | A | 0 |
| 125 | 0 | C | 0 |
| 125 | 0 | 0 | A |
内容的提问来源于stack exchange,提问作者jennytrinh96
相关产品推荐
相关产品推荐

