如何更改.npz文件中的值? [英] How do I change a value in a .npz file?

查看:673
本文介绍了如何更改.npz文件中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改 npz 文件中的一个值.

I want to change one value in an npz file.

npz文件包含多个npy,我希望除一个以外的所有内容('run_param')保持不变,我想保存原始文件.

The npz file contains several npy's, I want all but one ( 'run_param' ) to remain unchanged and I want to save over the original file.

这是我的工作代码:

DATA_DIR = 'C:\\Projects\\Test\\data\\'
ass_file = np.load( DATA_DIR + 'assumption.npz' )
run_param = ass_file['run_param']

print ass_file['run_param'][0]['RUN_MODE']
ass_file['run_param'][0]['RUN_MODE'] = 1        (has no effect)
print ass_file['run_param'][0]['RUN_MODE']

print run_param[0]['RUN_MODE']
run_param[0]['RUN_MODE'] = 1
print run_param[0]['RUN_MODE']

这将产生:

0
0
0
1

我似乎无法更改原始npy中的值.

I can't seem to change the value in the original npy.

我以后要保存的代码是:

My code to save afterward is:

np.savez( DATA_DIR + 'assumption.npz', **ass_file )   #
ass_file.close()

如何进行这项工作?

推荐答案

为什么您的代码不起作用

np.load获得的是 NpzFile ,它看起来像是字典,但实际上不是.每次您访问一个(如果有)项目时,它都会从文件中读取数组,并返回一个新对象.演示:

Why your code did not work

What you get from np.load is a NpzFile, which may look like a dictionary but isn't. Every time you access one if its items, it reads the array from file, and returns a new object. To demonstrate:

>>> import io
>>> import numpy as np
>>> tfile = io.BytesIO()  # create an in-memory tempfile
>>> np.savez(tfile, test_data=np.eye(3))  # save an array to it
>>> tfile.seek(0)  # to read the file from the start
0
>>> npzfile = np.load(tfile)
>>> npzfile['test_data']
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> id(npzfile['test_data'])
65236224
>>> id(npzfile['test_data'])
65236384
>>> id(npzfile['test_data'])
65236704

同一对象的id函数始终相同.从 Python 3手册:

The id function for the same object is always the same. From the Python 3 Manual:

id (对象) 返回对象的身份".这是一个整数,可以保证在此对象的生存期内唯一且恒定. ...

id(object) Return the "identity" of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. ...

这意味着在我们的情况下,每次调用npz['test_data']都会得到一个新对象.进行这种延迟读取"是为了保留内存并仅读取所需的数组.在您的代码中,您修改了该对象,但随后将其丢弃并稍后再读取一个新对象.

This means that in our case, each time we call npz['test_data'] we get a new object. This "lazy reading" is done to preserve memory and to read only the required arrays. In your code, you modified this object, but then discarded it and read a new one later.

如果npzfile是这个奇怪的NpzFile而不是字典,我们可以简单地将其转换为字典:

If the npzfile is this weird NpzFile instead of a dictionary, we can simply convert it to a dictionary:

>>> mutable_file = dict(npzfile)
>>> mutable_file['test_data'][0,0] = 42
>>> mutable_file
{'test_data': array([[ 42.,   0.,   0.],
                     [  0.,   1.,   0.],
                     [  0.,   0.,   1.]])}

您可以随意编辑字典并保存.

You can edit the dictionary at will and save it.

这篇关于如何更改.npz文件中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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