我有一个形状为[1953,949,13]的3D Numpy数组。我想将其写入CSV文件,其中每行应包含2D形状的数组[949 13],而csv文件应包含1953行。我尝试了 np.savetext ,它仅支持1D和2D数组。然后,我尝试逐行写入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)

关于python - 将3D Numpy数组写入CSV文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50459119/

10-12 12:45
查看更多