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

如何将DataFrame列中的嵌套列表转换为一维字符串列表?

DataFrame嵌套列表列批量扁平化方法

1. 两层嵌套场景核心实现(适配你给出的示例格式)

直接搭配pandas的apply方法和列表推导式即可完成批量转换:

import pandas as pd

# 假设你存储嵌套列表的列名为nested_col
df["flat_col"] = df["nested_col"].apply(
    lambda x: [item for sublist in x for item in sublist]
)

效果验证

用你提供的示例数据做测试:

# 构造测试DataFrame
df = pd.DataFrame(
    {
        "nested_col": [
            [["Petitioner Jae Lee", "his", "he"], []],
            [["lee"], ["federal officials"]],
            [[], ["lawyer"]],
        ]
    }
)

# 执行转换
df["flat_col"] = df["nested_col"].apply(
    lambda x: [item for sublist in x for item in sublist]
)

print(df["flat_col"].tolist())

输出完全匹配预期:

[
    ['Petitioner Jae Lee', 'his', 'he'],
    ['lee', 'federal officials'],
    ['lawyer']
]

2. 任意深度嵌套通用实现

如果数据中存在超过两层的嵌套列表,可使用递归函数做通用打平:

def flatten_any_depth(nested):
    res = []
    for elem in nested:
        if isinstance(elem, list):
            res.extend(flatten_any_depth(elem))
        else:
            res.append(elem)
    return res

# 批量调用
df["flat_col"] = df["nested_col"].apply(flatten_any_depth)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:54:04