将3D Numpy数组写入CSV文件

时间:2018-05-22 02:55:39

标签: python arrays numpy

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

的问题不同

2 个答案:

答案 0 :(得分:1)

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

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)

答案 1 :(得分:1)

我改用了这种方法,没有发现更好的方法:

# 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])