如何在循环中使用`numpy.savez`来保存多个numpy数组?

时间:2017-03-12 15:50:59

标签: python arrays numpy save

我想在循环中使用numpy.savez多次保存多个numpy数组,这是一个例子:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([5, 6, 12])

for i in range(3):
    np.savez("file_info", info1 = a, info2 = b)
    print('a => ', a)
    print('b => ', b)
    a = a * 3
    b = b * 2

输出:

a =>  [1 2 3]
b =>  [ 5  6 12]
a =>  [3 6 9]
b =>  [10 12 24]
a =>  [ 9 18 27]
b =>  [20 24 48]

但是当我读到保存的文件时:

npzfile = np.load("file_info.npz")
npzfile['info1']

我只得到最后一个数组(因为每个循环都删除了内容):

array([ 9, 18, 27])

所以,我的问题是,如何将所有numpy数组保存在同一个文件中?

1 个答案:

答案 0 :(得分:2)

当您保存同名的新文件时,它会覆盖旧文件。为什么不让你的存档退出你的for循环:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([5, 6, 12])

save_info = np.zeros([3, 2, 3]) #array to store all the info
#one dimension for each entry in a, one for as many arrays as you have
#generating info, and one for the number of times you'll loop over it

for i in range(3): #therefore i will be [0, 1, 2]
    save_info[:, 0, i] = a #save from the a array
    save_info[:, 1, i] = b #save from the b array
    a = a * 3
    b = b * 2

np.savez("file_info", info1=save_info) #save outside for loop doesn't overwrite

然后我可以从文件中读取信息:

>>> import numpy as np
>>> data = np.load("file_info.npz") #load file to data object
>>> data["info1"]
array([[[  1.,   3.,   9.],
        [  5.,  10.,  20.]],

       [[  2.,   6.,  18.],
        [  6.,  12.,  24.]],

       [[  3.,   9.,  27.],
        [ 12.,  24.,  48.]]])

编辑: 或者,如果您要避免创建一个大型数组,则可以重命名每次循环时保存的文件:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([5, 6, 12])

for i in range(3): #therefore i will be [0, 1, 2]
    np.savez("file_info_"+str(i), info1=a, info2=b)
    #will save to "file_info_0.npz" on first run
    #will save to "file_info_1.npz" on second run
    #will save to "file_info_2.npz" on third run

    a = a * 3
    b = b * 2

编辑: 您可能更喜欢制作两个较小的数组,一个用于a,一个用于b:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([5, 6, 12])

save_a = np.zeros([3, 3]) #array to store all the a runs
save_b = np.zeros([3, 3]) #array to store all the b runs

for i in range(3): #therefore i will be [0, 1, 2]
    save_a[:, i] = a #save from the a array
    save_b[:, i] = b #save from the b array
    a = a * 3
    b = b * 2

np.savez("file_info", info1=save_a, info2=save_b) #save outside for loop doesn't overwrite