如何从npy.gz文件恢复numpy数组 [英] How to recover a numpy array from npy.gz file

查看:139
本文介绍了如何从npy.gz文件恢复numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用以下代码保存了许多numpy对象:

I've saved a number of numpy objects with the following code:

f = gzip.GzipFile('/some/path/file.npy.gz', "w")
np.save(file=f, arr=np.rint(trimmed).astype('int16'))
f.close()

现在我有一堆npy.gz文件,但是我不知道如何以编程方式将它们返回到python中. np.fromtextnp.fromstring似乎无效,也不会保留形状信息.

And now I have a bunch of npy.gz files, but I can't figure out how to programmatically return them back into python. np.fromtext or np.fromstring don't seem to work, and wouldn't preserve shape information anyway.

我尝试过:

gzipfile = gzip.GzipFile('/some/path/file.npy.gz', 'rb')
text = gzipfile.read() 

text看起来像这样:

b'\x93NUMPY\x01\x00F\x00{\'descr\': \'<i2\', \'fortran_order\': False, \'shape\': (132, 248, 291), } \n0\xf80\xf80...'

但是接下来我该怎么做才能将该字符串返回到一个numpy对象中?

But what can I do next to get that string back into a numpy object?

推荐答案

如果它可以对save转换为gzip文件,则也可以从一个文件读取. loadsave的对应物:

If it works to save to a gzip file, it might also work to read from one. load is the counterpart to save:

In [193]: import gzip
In [194]: f = gzip.GzipFile('file.npy.gz', "w")
In [195]: np.save(f, np.arange(100))
In [196]: f.close()

In [200]: f = gzip.GzipFile('file.npy.gz', "r")
In [201]: np.load(f)
Out[201]: 
array([ 0,  1,  2,  3,  4,  .... 98, 99])

还有一个savez(compressed)可以将多个数组保存到zip存档中.

There is also a savez(compressed) that saves multiple arrays to a zip archive.

这篇关于如何从npy.gz文件恢复numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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