gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:12:21 28 4
gpt4 key购买 nike

我想在循环中使用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 数组保存在同一个文件中?

最佳答案

当您保存同名的新文件时,它会覆盖旧文件。为什么不将保存从 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

关于python - 如何在循环中使用 `numpy.savez`来保存多个numpy数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749520/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com