Your example
是一个 3d 数组
In [82]: example=np.array([[[i for i in range(0, 5)],[0 for j in range(0, 5)]] for k in range(0, 3)]) # chg 10 to 3 for display
In [83]: example.shape
Out[83]: (3L, 2L, 5L)
In [84]: example
Out[84]:
array([[[0, 1, 2, 3, 4],
[0, 0, 0, 0, 0]],
[[0, 1, 2, 3, 4],
[0, 0, 0, 0, 0]],
[[0, 1, 2, 3, 4],
[0, 0, 0, 0, 0]]])
尝试保存整个内容会导致错误(由于版本不同而有不同的消息):
In [87]: np.savetxt('test.csv',example, delimiter=',')
....
TypeError: float argument required, not numpy.ndarray
但保存一“行”就可以了
In [88]: np.savetxt('test.csv',example[1,...], delimiter=',')
以整数格式保存可以使输出更漂亮
In [94]: np.savetxt('test.csv',example[1,...], delimiter=',',fmt='%d')
In [95]: with open('test.csv') as f:print f.read()
0,1,2,3,4
0,0,0,0,0
那么你希望如何保存 3d 数组呢?请记住您将如何使用它/阅读它。多个文件?一个文件内有多个块?
https://stackoverflow.com/a/3685339/901925是一个关于如何保存 3d 数组的 6 年前的答案。简单的答案是打开一个文件,然后执行多个savetxt
对于数组的切片。这将数据保存在块中。但是加载这些块是另一个SO问题(之前已经出现过)。
In [100]: with open('test.csv','w') as f:
...: for row in example:
...: np.savetxt(f,row,delimiter=',',fmt='%d',footer='====')
...:
In [101]: with open('test.csv') as f:print f.read()
0,1,2,3,4
0,0,0,0,0
# ====
0,1,2,3,4
0,0,0,0,0
# ====
0,1,2,3,4
0,0,0,0,0
# ====
为了回应你的评论,这有效
example=np.ones((4,2,100))
np.savetxt('test.csv',example[1,...], delimiter=',',fmt='%.18e')
保存 3d 数组的另一种方法是将其重塑为 2d。加载后,您可以将其重新整形回 3D,可能使用您存储在注释行中的信息
np.savetxt('test.csv',example.reshape(-1,example.shape[-1]), delimiter=',',fmt='%.18e')