将一个3D的Numpy数组写入CSV文件

8
我有一个形状为[1953, 949, 13]的3D Numpy数组。我想将它写入CSV文件中,其中每行应该包含一个形状为[949,13]的2D数组,csv文件应该包含1953行。我尝试过np.savetext,但它仅支持1D和2D数组。然后我尝试逐行写入CSV,但它需要将每个矩阵转换为字符串。在Python中如何完成这个操作?我的需求与问题“将值存储在3D数组中”不同。

3
可能是Python:将值存储在3D数组中到csv的重复问题。 - Sebastian Mendez
2
如何将3D结构显示为简单的行和列?并使用期望相同CSV布局的代码进行读取?没有某种形式的操作是不可能的。基本上,要么重新塑造成2D,要么将平面保存为单独的2D块。由您决定CSV应该看起来像什么。 - hpaulj
@hpaulj明白了。谢谢。 - rpb
@Sebastian 我希望在CSV的每一行中写入2D矩阵。我检查了你指出的问题的答案,但这里的要求有点不同。 - rpb
2个回答

7
我不确定这是否是最佳方法,但我曾遇到相同的问题,以下是我的解决方法。
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)

这个解决方案更普遍并且运作得非常好。 - Vahid

4

我使用了这种方法,没有意识到有更好的方法:

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

2
我认为这个解决方案更加高效! - Vahid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接