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

博客介绍了Python中使用np.load读取npz文件的问题。从np.load得到的NpzFile看似字典却不同,每次访问项目会读取新数组。这种‘懒惰读取’可节省内存,但修改对象会被丢弃。还给出解决办法,可将NpzFile转换为字典进行编辑和保存。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

为什么你的代码不起作用

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

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

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值