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

3D numpy array转换为pandas DataFrame(替代已弃用的Panel实现)

3D Numpy数组转Pandas DataFrame实现方案

实现逻辑

  • 直接通过numpy高级索引批量提取目标列,避免使用已弃用的Panel
  • 转置后直接构造DataFrame,时间复杂度为O(n),性能优于循环遍历的实现

完整代码

import numpy as np
import pandas as pd

# 生成示例3D数组
x = np.random.rand(100, 4, 4)

# 核心转换逻辑
# x[:, :, 0]提取所有4x4矩阵的第0列,得到形状(100,4)的数组,转置后为(4,100)
df = pd.DataFrame(
    x[:, :, 0].T,
    columns=[f"column{i+1}" for i in range(x.shape[0])]
)

正确性验证

可以通过以下代码验证转换结果符合要求:

# 验证column1等于x[0][:,0]
print((df["column1"] == x[0, :, 0]).all())
# 验证column2等于x[1][:,0]
print((df["column2"] == x[1, :, 0]).all())

以上代码运行输出均为True,说明转换符合规则要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:48:03