我有一个形状为[1953, 949, 13]的3D Numpy数组。我想将它写入CSV文件中,其中每行应该包含一个形状为[949,13]的2D数组,csv文件应该包含1953行。我尝试过np.savetext,但它仅支持1D和2D数组。然后我尝试逐行写入CSV,但它需要将每个矩阵转换为字符串。在Python中如何完成这个操作?我的需求与问题“将值存储在3D数组中”不同。
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)
我使用了这种方法,没有意识到有更好的方法:
# reshaping the array from 3D matrice to 2D matrice.
arrReshaped = arr.reshape(arr.shape[0], -1)
# saving reshaped array to file.
np.savetxt(filename, arrReshaped)
# retrieving data from file.
loadedArr = np.loadtxt(filename)
# This loadedArr is a 2D array, therefore we need to convert it to the original array shape.
# reshaping to get original matrice with original shape.
loadedOriginal = loadedArr.reshape(loadedArr.shape[0], loadedArr.shape[1] // arr.shape[2], arr.shape[2])