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

如何将Pandas DataFrame中列的列表元素展开为行并复制其他列值?

解决Pandas列表列展开为多行的问题

嘿,这个需求其实用Pandas的explode()方法就能轻松搞定,这也是现在最推荐的方案!下面给你分步演示:

步骤1:构造原始DataFrame

首先先把你给出的示例数据构建出来:

import pandas as pd

df = pd.DataFrame({
    'col1': [1, 2, 3],
    'col2': [[1,2,3], [1,2], [1]]
})

步骤2:使用explode()方法展开列表

从Pandas 0.25版本开始,官方提供了explode()方法,专门用来处理这种把列表/Series类型的列拆分为多行的场景,其他列会自动复制对应的值:

df_exploded = df.explode('col2', ignore_index=True)
  • 参数ignore_index=True是用来重置结果的索引,避免出现重复的原索引;如果不需要重置索引,可以去掉这个参数。

运行后得到的结果就是你想要的结构:

col1col2
11
12
13
21
22
31

兼容旧版本Pandas的替代方案

如果你使用的Pandas版本低于0.25(不推荐,建议升级),可以用apply()结合stack()来实现:

df_exploded = (df.apply(lambda x: pd.Series(x['col2'], index=[x['col1']]*len(x['col2'])), axis=1)
               .stack()
               .reset_index(level=0, name='col2')
               .reset_index(drop=True))

这个方法的逻辑是:对每一行,把col2的列表转为Series,索引用col1的值重复对应次数;然后用stack()展开为多层索引,最后重置索引得到目标结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:42:50