如何用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
相关产品推荐
相关产品推荐

