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

如何用Python读取CSV并将分片数据转换为3D数组?

解决方案

手动逐行解析生成3D数组

由于numpy.loadtxt和pandas无法直接识别#new slice作为3D维度的分隔符,需要手动处理文件内容:

import numpy as np

def load_3d_slices(file_path):
    3d_data = []
    current_2d = []

    with open(file_path, 'r') as fp:
        for line in fp:
            stripped_line = line.strip()
            # 跳过空行和非切片分隔符的注释行
            if not stripped_line or (stripped_line.startswith('#') and stripped_line != '#new slice'):
                continue
            # 触发切片分割,保存当前2D数组并重置
            if stripped_line == '#new slice':
                if current_2d:
                    3d_data.append(np.array(current_2d, dtype=int))
                    current_2d = []
                continue
            # 解析数据行,转换为整数列表
            row_values = list(map(int, stripped_line.split('; ')))
            current_2d.append(row_values)
        # 处理最后一个未被分隔符收尾的切片
        if current_2d:
            3d_data.append(np.array(current_2d, dtype=int))
    
    return np.array(3d_data)

# 调用示例
irdata = load_3d_slices('your_data.csv')
print(irdata)

关键细节说明

  • 适配文件分隔符:代码默认按; (分号+空格)分割数据,若实际格式不同,修改split的参数即可。
  • 数据类型调整:如果你的数据是浮点数,将dtype=int改为dtype=float即可。
  • 注释处理:自动跳过开头的描述性注释,仅将#new slice作为切片分隔标记。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:10:31