rpb*_*rpb 5 python arrays numpy
我有一个形状为 [1953,949,13] 的 3D Numpy 数组。我想将它写入一个 CSV 文件,其中每行应包含一个形状为 [949 13] 的二维数组,而 csv 文件应包含 1953 行。我试过np.savetext它只支持一维和二维数组。然后我尝试逐行写入 CSV,但它需要将每个矩阵转换为字符串。我怎样才能在 python 中完成这项工作?我的要求与将 3D 数组中的值存储到 csv 的问题不同
小智 5
我不确定这是否是最好的方法,但我遇到了同样的问题,这是我解决它的方法。
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)
Run Code Online (Sandbox Code Playgroud)