加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何更改.npz文件中的值?

发布时间:2020-12-20 11:37:50 所属栏目:Python 来源:网络整理
导读:我想在npz文件中更改一个值. npz文件包含几个npy,我希望除了一个(‘run_param’)之外的所有文件保持不变,我想保存原始文件. 这是我的工作代码: DATA_DIR = 'C:ProjectsTestdata'ass_file = np.load( DATA_DIR + 'assumption.npz' )run_param = ass_
我想在npz文件中更改一个值.

npz文件包含几个npy,我希望除了一个(‘run_param’)之外的所有文件保持不变,我想保存原始文件.

这是我的工作代码:

DATA_DIR = 'C:ProjectsTestdata'
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中的值.

我之后保存的代码是:

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

如何使这项工作?

解决方法

为什么你的代码不起作用

你从np.load得到的是一个NpzFile,它可能看起来像字典但不是.每次访问一个项目时,它都会从文件中读取数组,并返回一个新对象.展示:

>>> 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.,1.]])
>>> id(npzfile['test_data'])
65236224
>>> id(npzfile['test_data'])
65236384
>>> id(npzfile['test_data'])
65236704

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

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’]时我们都会得到一个新对象.这种“懒惰读取”是为了保留内存并只读取所需的数组.在您的代码中,您修改了此对象,但随后将其丢弃并稍后读取新对象.

所以,我们能做些什么?

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读