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

如何将存储列表元素的dataframe转换为shape(4,200,3)的3D数组

DataFrame转形状(4,200,3)的3D数组解决方案

你直接调用np.array(df)得到形状为(4,3)的二维数组,是因为当前DataFrame的每个单元格存储的是长度为200的列表,numpy默认会将每个列表识别为单个object类型的元素,不会自动展开内部的数值。你可以用以下几种方法实现目标转换:


方法1:逐行堆叠(逻辑直观易理解)

逐行处理每行的3个列表,将其按最后一维堆叠后再合并所有行的数据:

import numpy as np

arr = np.stack([np.stack(row, axis=1) for _, row in df.iterrows()])
print(arr.shape) # 输出 (4, 200, 3)

方法2:向量化操作(性能更高,适合大数据量场景)

无需循环,通过数组拼接和维度换位实现转换,运行效率更高:

import numpy as np

# 先把所有单元格的列表拼接为一维大数组
flat_arr = np.concatenate(df.to_numpy().flatten())
# 重塑维度后调整维度顺序得到目标结构
arr = flat_arr.reshape(4, 3, 200).transpose(0, 2, 1)
print(arr.shape) # 输出 (4, 200, 3)

方法3:简洁写法(基于pandas原生接口)

代码最简洁,适合小数据集快速转换:

import numpy as np
import pandas as pd

arr = np.array(df.apply(lambda x: np.array(x.to_list()), axis=1).to_list())
print(arr.shape) # 输出 (4, 200, 3)

内容的提问来源于stack exchange,提问作者Darshan s p

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:18:04