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

2024-03-12

我想改变一个值npz file.

The npz文件包含几个npy的,我想要除了一个以外的所有('run_param' )保持不变,我想保存原始文件。

这是我的工作代码:

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.

我随后保存的代码是:

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

如何使这项工作有效?


为什么你的代码不起作用

你从中得到什么np.load is a NpzFile https://github.com/numpy/numpy/blob/5ac270b06e411dd0e13108ed5dafad31d5ab589d/numpy/lib/npyio.py#L104,它可能看起来像一本字典,但事实并非如此。每次访问它的项目时,它都会从文件中读取数组,并返回一个新对象。展示:

>>> 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

The id同一个对象的函数总是相同的。来自Python 3 手册 https://docs.python.org/3/library/functions.html#id:

id(object) 返回对象的“身份”。这是一个整数,保证该对象在其生命周期内是唯一且恒定的。 ...

这意味着在我们的例子中,每次我们调用npz['test_data']我们得到一个新对象。执行这种“惰性读取”是为了保留内存并仅读取所需的数组。在您的代码中,您修改了该对象,但随后将其丢弃并稍后读取一个新对象。


所以,我们能做些什么?

If the npzfile这很奇怪吗NpzFile我们可以简单地将其转换为字典,而不是字典:

>>> 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.]])}

您可以随意编辑词典并保存。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何更改 .npz 文件中的值? 的相关文章

随机推荐