使用np.savetxt和np.loadtxt用多维数组 [英] Using np.savetxt and np.loadtxt with multi-dimensional arrays
问题描述
什么是存储更比2维数组的通用方式( NDIM> 2
)到文件,并使用相同的格式(尺寸)检索它 np.savetxt
和 np.loadtxt
?
What is a generalized way of storing a more-than-2 dimensional array (ndim > 2
) to file and retrieving it in same format (dimension) using np.savetxt
and np.loadtxt
?
我担心的是,如果我给出任何分隔符,同时存储,我需要给一些治疗方法,同时获取?加上花车处理,并在相同的格式检索它是有点棘手。
My concern is if I give any delimiter while storing, do I need to give some treatments while retrieving? Plus dealing with floats and retrieving it in same format is little tricky.
我已经看到了很多文档简单的例子。我只是好奇,是否最简单的存储 np.savetxt(文件名,数组)
可以用简单的 =阵列np.loadtxt(文件名)进行检索
或没有。
I have seen many simple examples in the docs. I am just curious about whether the simplest storing np.savetxt(filename, array)
can be retrieved using simply array = np.loadtxt(filename)
or not.
推荐答案
如果您需要保存多维数组中的文本文件,你可以使用头
参数保存原始阵列形状:
If you need to save multi-dimensional arrays in a text file you can use the header
parameter to save the original array shape:
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=',')
和加载该阵列可以这样做:
And to load this array you can do:
with open('test.txt') as f:
shape = map(int, f.next()[1:].split(','))
b = np.genfromtxt(f, delimiter=',').reshape(shape)
这篇关于使用np.savetxt和np.loadtxt用多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!