如何在Python中将含列表列的DataFrame展开为指定格式?
Pandas 展开DataFrame多列列表的实现方法
要实现将包含列表的func_list和func_id列按元素拆分展开,同时保留其他列的对应值,直接使用Pandas的explode方法即可,具体步骤如下:
- 构造示例DataFrame(模拟原始数据)
import pandas as pd df = pd.DataFrame({ 'sect_id': [0, 1], 'sector': ['AAA', 'BBB'], 'func_list': [['A', 'B'], ['C', 'D']], 'func_id': [[1, 2], [3, 4]] })
- 调用
explode方法同时展开多列
expanded_df = df.explode(['func_list', 'func_id'], ignore_index=True)
执行后expanded_df的结构即为目标格式:
| sect_id | sector | func_list | func_id |
|---|---|---|---|
| 0 | AAA | A | 1 |
| 0 | AAA | B | 2 |
| 1 | BBB | C | 3 |
| 1 | BBB | D | 4 |
说明
explode方法会将指定列的每个列表元素拆分为独立行,自动复制其他列的对应值ignore_index=True参数用于重置结果的索引,避免出现重复索引问题
内容的提问来源于stack exchange,提问作者nuttychan
相关产品推荐
相关产品推荐

