Skip to main content
 首页 » 编程设计

python之将 3D Numpy 数组写入 CSV 文件

2024年12月31日8txw1958

我有一个形状为 [1953,949,13] 的 3D Numpy 数组。我想将它写入一个 CSV 文件,其中每一行应包含一个形状为 [949 13] 的二维数组,而 csv 文件应包含 1953 行。我试过 np.savetext,它只支持一维和二维数组。然后我尝试逐行写入 CSV,但它需要将每个矩阵转换为字符串。我怎样才能在 python 中完成这个?我的要求不同于将 3D 数组中的值存储到 csv 的问题

请您参考如下方法:

我不确定这是否是最好的方法,但我遇到了同样的问题,下面是我的解决方法。

import csv 
import numpy as np 
fil_name = 'file' 
example = np.zeros((2,3,4)) 
example = example.tolist() 
with open(fil_name+'.csv', 'w', newline='') as csvfile: 
    writer = csv.writer(csvfile, delimiter=',') 
    writer.writerows(example) 
 
#to read file you saved 
with open(fil_name+'.csv', 'r') as f: 
  reader = csv.reader(f) 
  examples = list(reader) 
 
print(examples) 
nwexamples = [] 
for row in examples: 
    nwrow = [] 
    for r in row: 
        nwrow.append(eval(r)) 
    nwexamples.append(nwrow) 
print(nwexamples)