从python中的numpy npz文件加载数组 [英] Loading arrays from numpy npz files in python

查看:531
本文介绍了从python中的numpy npz文件加载数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常将数据保存在python的npz文件中.如何编写一个加载npz文件并自动创建.npz文件中存在的数组的函数.例如,假设在名为some_data.npz的文件中存在三个数组ABC.

I usually save data in npz files in python. How to write a function which loads the npz file and automatically creates arrays which are present in the .npz file. For example, say there are three arrays A, B, and C in a file named some_data.npz.

我希望函数执行的操作是将npz文件加载为

What I want the function to do is load the npz file as

data1 = np.load('some_data.npz')

,然后自动创建三个名为data1Adata1Bdata1C的数组,该数组存储原始.npz文件中的数组ABC.该怎么做?

and then automatically create three arrays named data1A, data1B and data1C which stores the arrays A, B, and C from the original .npz file. How to do this?

推荐答案

如果要创建名称,请将数组存储在dict中:

If you want to create names store the arrays in a dict:

a1 = np.array([1,2,3])
a2 = np.array([4,5,6])
a3 = np.array([7,8,9])

np.savez("test", A=a1,B=a2,C=a3)
a = np.load("test.npz")
d = dict(zip(("data1A","data1B","data1C"), (a[k] for k in a)))
print(d)
{'data1A': array([4, 5, 6]), 'data1C': array([7, 8, 9]), 'data1B': array([1, 2, 3])}

如果要创建键而不显式传递名称:

If you want to create the keys without passing the names explicitly:

a1 = np.array([1, 2, 3])
a2 = np.array([4, 5, 6])
a3 = np.array([7, 8, 9])

np.savez("test", A=a1,B=a2,C=a3)
a = np.load("test.npz")

d = dict(zip(("data1{}".format(k) for k in a), (a[k] for k in a)))
print(d)

这篇关于从python中的numpy npz文件加载数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆