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

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

如何让它发挥作用?

最佳答案

为什么你的代码不起作用

你从 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(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.,   0.],
                     [  0.,   1.,   0.],
                     [  0.,   0.,   1.]])}

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

关于python - 如何更改 .npz 文件中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25891186/

相关文章:

python - 在 CSV 文件/Pandas Dataframe 中查找标题行的行号

python - 按值排序元组列表,然后按字母顺序排序

python - np.savetxt 输出 float 据需要哪个参数?

python - Numpy: "Adding"索引和冒号

python - 将二维数组添加到具有快速不断变化的索引的三维数组

python - 工厂调用备用构造函数(类方法)

python - Kivy Python 中的下拉菜单

python - Python-如何与另一个脚本共享实时数据

python - 当数组具有不同长度的字符串时,记录数组上的 numpy.concatenate 失败

image - 过滤 numpy 数组并将数组重新堆叠为多维矩阵