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

如何在Pandas中同时对日期列和关联列执行unnest/explode展开操作

多列同步展开解决方法

pandas 0.25及以上版本的explode原生支持多列同步展开,只要保证每行两个待展开列的列表长度一致,就会按位置一一对应展开,不会出现错位问题。

完整实现代码

import pandas as pd

# 构造原始DataFrame
data = [
    ["ABC", 2002, ["AB", "AB", "EF"], ["2002-05-06", "2002-05-07", "2002-05-12"]],
    ["DEF", 2002, [["CD", "EF"]], ["2002-06-12", "2002-06-13"]],
    ["GHI", 2002, [["JK"]], ["2002-03-02"]],
    ["JKL", 2002, [[]], ["2002-03-02"]],
]
df = pd.DataFrame(data, columns=["ID", "year", "list", "date_list"])

# 预处理list列,统一每行长度和date_list匹配
def adjust_list_length(row):
    current_list = row["list"]
    target_length = len(row["date_list"])
    # 长度匹配直接返回
    if len(current_list) == target_length:
        return current_list
    # 嵌套列表且内层长度匹配时拆外层
    if len(current_list) == 1 and isinstance(current_list[0], list) and len(current_list[0]) == target_length:
        return current_list[0]
    # 其他场景保留原列表
    return current_list

df["list"] = df.apply(adjust_list_length, axis=1)

# 同步展开两列
result_df = df.explode(["list", "date_list"], ignore_index=True)

# 按需求将展开后的元素包回列表格式
result_df["list"] = result_df["list"].apply(lambda x: [x] if not isinstance(x, list) else x)
result_df["date_list"] = result_df["date_list"].apply(lambda x: [x])

注意事项

  • 执行多列explode前必须保证两个待展开列的每行列表长度一致,否则会抛出报错
  • 如果你实际场景中不存在嵌套列表长度不匹配的问题,可以直接省略预处理步骤,直接调用df.explode(['list', 'date_list'], ignore_index=True)即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:18:02