问题描述
我处理不同形状的数组,我想用 numpy.save
保存它们,所以,考虑我有
I working on different shapes of arrays and I want to save them all with numpy.save
, so, consider I have
mat1 = numpy.arange(8).reshape(4, 2)
mat2 = numpy.arange(9).reshape(2, 3)
numpy.save('mat.npy', numpy.array([mat1, mat2]))
它有效.但是当我有两个具有相同大小的维度的矩阵时,它不起作用.
It works. But when I have two matrices with one dimension of same size it's not working.
mat1 = numpy.arange(8).reshape(2, 4)
mat2 = numpy.arange(10).reshape(2, 5)
numpy.save('mat.npy', numpy.array([mat1, mat2]))
导致回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中ValueError:无法将输入数组从形状(2,4)广播到形状(2)
并注意由 numpy.array([mat1, mat2])
而不是由 numpy.save
And note that the problem caused by numpy.array([mat1, mat2])
and not by numpy.save
我知道这样的数组是可能的:
I know that such array is possible:
>>numpy.array([[[1, 2]], [[1, 2], [3, 4]]])数组([[[1, 2]], [[1, 2], [3, 4]]], dtype=object)
所以,我想要的是同时将两个数组保存为 mat1
和 mat2
.
So, all of what I want is to save two arrays as mat1
and mat2
at once.
推荐答案
If you'd like to save multiple arrays in the same format as np.save
, use np.savez
.
例如:
import numpy as np
arr1 = np.arange(8).reshape(2, 4)
arr2 = np.arange(10).reshape(2, 5)
np.savez('mat.npz', name1=arr1, name2=arr2)
data = np.load('mat.npz')
print data['name1']
print data['name2']
如果有多个数组,可以展开参数:
If you have several arrays, you can expand the arguments:
import numpy as np
data = [np.arange(8).reshape(2, 4), np.arange(10).reshape(2, 5)]
np.savez('mat.npz', *data)
container = np.load('mat.npz')
data = [container[key] for key in container]
请注意,不会保留顺序.如果您确实需要保留顺序,您可以考虑使用 pickle
代替.
Note that the order is not preserved. If you do need to preserve order, you might consider using pickle
instead.
如果您使用pickle
,请务必指定二进制协议,否则您将使用ascii pickle 编写东西,这对于numpy 数组尤其低效.使用二进制协议,ndarray
或多或少会选择与 np.save
/np.savez
相同的格式.例如:
If you use pickle
, be sure to specify the binary protocol, otherwise the you'll write things using ascii pickle, which is particularly inefficient for numpy arrays. With a binary protocol, ndarray
s more or less pickle to the same format as np.save
/np.savez
. For example:
# Note: This is Python2.x specific. It's identical except for the import on 3.x
import cPickle as pickle
import numpy as np
data = [np.arange(8).reshape(2, 4), np.arange(10).reshape(2, 5)]
with open('mat.pkl', 'wb') as outfile:
pickle.dump(data, outfile, pickle.HIGHEST_PROTOCOL)
with open('mat.pkl', 'rb') as infile:
result = pickle.load(infile)
在这种情况下,result
和 data
将具有相同的内容,并且将保留输入数组列表的顺序.
In this case, result
and data
will have identical contents and the order of the input list of arrays will be preserved.
这篇关于NumPy 一次性保存一些数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!