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

如何在Python中将含列表列的DataFrame展开为指定格式?

Pandas 展开DataFrame多列列表的实现方法

要实现将包含列表的func_list和func_id列按元素拆分展开,同时保留其他列的对应值,直接使用Pandas的explode方法即可,具体步骤如下:

  1. 构造示例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]]
})
  1. 调用explode方法同时展开多列
expanded_df = df.explode(['func_list', 'func_id'], ignore_index=True)

执行后expanded_df的结构即为目标格式:

sect_idsectorfunc_listfunc_id
0AAAA1
0AAAB2
1BBBC3
1BBBD4

说明

  • explode方法会将指定列的每个列表元素拆分为独立行,自动复制其他列的对应值
  • ignore_index=True参数用于重置结果的索引,避免出现重复索引问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:00:59