将多维数组 ( ndim > 2
) 存储到文件并使用 np.savetxt
以相同格式(维度)检索它的通用方法是什么?和 np.loadtxt
?
我担心的是,如果我在存储时给出任何定界符,我是否需要在检索时进行一些处理?此外,处理 float 并以相同的格式检索它有点棘手。
我在文档中看到了很多简单的例子。我只是好奇是否最简单的存储 np.savetxt(filename, array)
可以简单地使用 array = np.loadtxt(filename)
检索还是不是。
最佳答案
如果需要在文本文件中保存多维数组可以使用header
参数来保存原始数组形状:
import numpy as np
a = np.random.random((2, 3, 4, 5))
header = ','.join(map(str, a.shape))
np.savetxt('test.txt', a.reshape(-1, a.shape[-1]), header=header,
delimiter=',')
要加载这个数组,你可以这样做:
with open('test.txt') as f:
shape = map(int, f.next()[1:].split(','))
b = np.genfromtxt(f, delimiter=',').reshape(shape)
关于python - 将 np.savetxt 和 np.loadtxt 与多维数组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26234263/