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

如何替换Python DataFrame中存储的嵌套列表的值?

替换嵌套列表中的索引为对应DataFrame列值

问题背景

我有如下嵌套结构的DataFrame:

import pandas as pd

data = [[[[[1, 2, 0], [1]],[[1, 2], [4]]],
        [[[[1, 2], [4]]]], [[[1]]]], [[[[1, 2, 0], [1]],[[1, 2], [4]]],
        [[[[1, 2], [4]]]], [[[1]]]]]

df = pd.DataFrame(data)

同时还有第二个DataFrame df2:

data2 = [[1, 10], [1, 15], [1, 14], [1, 20], [1, 18]]
df2 = pd.DataFrame(data2, columns=['dir', 'line'])

需求:df中嵌套列表的数值代表df2的索引,需要将这些数值替换为df2里line列对应的取值,预期输出如下:

finalData = [[[[[15, 14, 10], [15]],[[15, 14], [20]]],
        [[[[15, 14], [20]]]], [[[15]]]], [[[[15, 14, 10], [15]],[[15, 14], [20]]],
        [[[[15, 14], [29]]]], [[[15]]]]]

finaldf = pd.DataFrame(finalData)

解决方案

由于列表嵌套层数不固定,我们可以编写一个递归函数来遍历所有嵌套层级,将每个索引值替换为df2.line对应的取值:

def replace_index_with_line(nested_list, line_series):
    # 遍历每个元素,判断是否为列表
    return [
        replace_index_with_line(item, line_series) if isinstance(item, list)
        else line_series.iloc[item]
        for item in nested_list
    ]

# 对df的每个元素应用递归替换函数
final_data = replace_index_with_line(df.values.tolist(), df2['line'])
finaldf = pd.DataFrame(final_data)

# 验证输出
print(finaldf)

说明

  • 递归函数replace_index_with_line会逐层遍历嵌套列表,遇到数值时就用df2.line.iloc[数值]取出对应的值,遇到列表则继续递归处理。
  • df.values.tolist()会把DataFrame转换成嵌套列表,方便递归处理,最后再转回DataFrame即可。

内容的提问来源于stack exchange,提问作者Anas.S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:25:25