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

时间:2014-09-17 12:55:51

标签: python numpy

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

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

如何使这项工作?

3 个答案:

答案 0 :(得分:6)

为什么你的代码不起作用

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

同一对象的id函数始终相同。来自Python 3 Manual

  

<强> ID 物体)    返回对象的“标识”。这是一个整数,在该生命周期内保证该对象是唯一且恒定的。 ...

这意味着在我们的情况下,每次调用npz['test_data']时,我们都会得到一个新对象。这种“懒惰读取”是为了保留内存并只读取所需的数组。在您的代码中,您修改了此对象,但随后将其丢弃并稍后读取新对象。

那我们该怎么办?

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

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

答案 1 :(得分:1)

numpy.savez ** kwds 一起使用,数组保存 关键字名称

   >>> outfile = TemporaryFile()
   >>> np.savez(outfile, x=x, y=y)
   >>> outfile.seek(0)
   >>> npzfile = np.load(outfile)
   >>> npzfile.files
   ['y', 'x']
   >>> npzfile['x']
   array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

而 使用savez和#34;只是&#34; *args 数组以默认名称保存

 >>> np.savez(outfile, x, y)
 >>> outfile.seek(0) # Only needed here to simulate closing & reopening file
 >>> npzfile = np.load(outfile)
 >>> npzfile.files
 ['arr_1', 'arr_0']
 >>> npzfile['arr_0']
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

重新阅读docstring numpy帮助并使用建议的语法。

   print numpy.savez.__doc__

答案 2 :(得分:0)

如果您有多个字段

您可能希望保留original structure,这是执行此操作的简单工作流程。

读取文件来判断

filename = "file.npz"
filedic = dict(np.load(filename))

修改条目

filedic['myentry'] = mynewvalue

写回文件

np.savez(filename, **filedic)
相关问题