首页 > 解决方案 > 将多个数据写入 csv,np 数组被转换为字符串

问题描述

我正在尝试将 pixel_array 数据和 PatientID 从多个 Dicom 文件写入 CSV。

像素数组,它们是 np 数组,像这样保存;

[[0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n ...\n [0 0 0 ... 0 0 0]\n [0 0 0 ...    0 0 0]\n [0 0 0 ... 0 0 0]]

如何取回原始的 np 数组?

如果你能给我一些关于将这些正确地写入 CSV 的建议,以便 np 数组保持原样?下面是循环

def tryer(a, b):   
if b == 'pixel_array':
    return(a.pixel_array)
else:
    try:
        return(getattr(a, b))
    except AttributeError:
        return('No')

tryer 定义如上;

a_list = ['PatientID', 'pixel_array']


with open('imgs_n_patied_train1.csv', 'w', newline = '') as f:
thewriter = writer(f)
thewriter.writerow(['PatientID', 'pixel_array\n'])
for i in imgs:
    #iterating through each file and writing all the metadata to a csv row-wise
    a = dicom.read_file(r'pathto\stage_2_train_images' + '\\' + i, force = True) 
    app = []
    for j in a_list:
        app.append(tryy.tryer(a, j))            
    thewriter.writerow(app)

标签: python-3.xpandasnumpyexport-to-csvpydicom

解决方案


推荐阅读