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

如何将含嵌套列表的Pandas DataFrame转换为指定格式的NumPy数组列表?

将Pandas DataFrame的列表元素转换为嵌套numpy数组列表

方案1:用apply快速实现

通过按行遍历+列表推导式完成元素转换,代码简洁高效:

import pandas as pd
import numpy as np

# 构建示例DataFrame
a = pd.DataFrame()
a['0'] = [[[0.2,0.4]], [[1, 10]]]
a['1'] = [[[4, 5]], [[6, 7]]]

# 执行转换
list_of_array = a.apply(lambda row: [np.array(item) for item in row], axis=1).tolist()

# 查看输出结果
print(list_of_array)

方案2:基础循环实现

如果需要更直观的逻辑,用iterrows逐行处理:

import pandas as pd
import numpy as np

a = pd.DataFrame()
a['0'] = [[[0.2,0.4]], [[1, 10]]]
a['1'] = [[[4, 5]], [[6, 7]]]

list_of_array = []
# 遍历DataFrame的每一行
for _, row in a.iterrows():
    # 将当前行的每个列表元素转为numpy数组
    row_arrays = [np.array(item) for item in row]
    list_of_array.append(row_arrays)

print(list_of_array)

最终输出

两种方法都会生成你需要的嵌套数组列表:

[[array([[0.2, 0.4]]), array([[4, 5]])], [array([[ 1, 10]]), array([[6, 7]])]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:52:07