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

如何在Pandas中将多列等长列表拆分为对应多行?

最优转换方法

针对你的需求,最简洁高效的方法是利用Pandas 1.3.0及以上版本支持的多列同步explode功能——因为你明确说明所有包含列表的列长度一致,这个特性可以完美匹配你的转换需求。

代码实现

import pandas as pd

# 源DataFrame
source_df = pd.DataFrame(data=[[1, [2, 3], [4, 5], [6, 7]], ['a', ['b', 'c'], ['d', 'e'], ['f', 'g']]])

# 对所有包含列表的列(索引1、2、3)执行同步explode
target_df = source_df.explode(list(source_df.columns[1:]), ignore_index=True)

# 可选:自动转换列数据类型(比如将数字列从object转为int)
target_df = target_df.convert_dtypes()

print(target_df)

效果说明

  • explode方法会将每一行中指定列的列表元素逐一展开,由于各列列表长度相等,展开后会自动保持元素的对应关系
  • 第一列的非列表值会自动重复,匹配展开后的行数
  • ignore_index=True用于重置最终DataFrame的索引,避免出现重复索引

兼容旧版Pandas(1.3.0以下)

如果你的Pandas版本较低,无法使用多列explode,可以采用apply结合列表配对的方式实现:

import pandas as pd

source_df = pd.DataFrame(data=[[1, [2, 3], [4, 5], [6, 7]], ['a', ['b', 'c'], ['d', 'e'], ['f', 'g']]])

# 逐行处理,将列表列元素按位置配对后构造新行
target_df = (
    source_df.apply(
        lambda row: pd.DataFrame([[row[0]] + vals for vals in zip(*row[1:])]),
        axis=1
    )
    .concat()
    .reset_index(drop=True)
)

print(target_df)

这个方法通过zip(*row[1:])将每行的列表列元素按位置配对,再结合第一列的值构造新的小DataFrame,最后合并所有结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:52:58