将键保存为npz的数据

问题描述 投票:0回答:1

我有一个矩阵A,我需要将其另存为npz文件,并用height键标记。我怎样才能做到这一点?

要将随机矩阵另存为npz,我正在使用以下代码:

import numpy as np
Test_matrix = np.random.rand(10,10)
np.savez('Matrix.npz', Test_matrix)

但是如果我加载文件并寻找height,则找不到任何内容:

M = np.load('Matrix.npz')
MM = M['height'].reshape(512,512)

给出错误'height is not a file in the archive'

python numpy
1个回答
1
投票

[就像评论说的那样,您永远不会告诉savez您要称其为“高度”。您可以通过将键作为**kwds传递来保存键。如果遇到任何给定功能,请确保将其设置为check the docs

而且您也无法将(10,10)调整为(512,512),所以我在这里已将其修正:

import numpy as np
Test_matrix = np.random.rand(512,512)
np.savez('Matrix.npz', height=Test_matrix)
M = np.load('Matrix.npz')
MM = M['height'].reshape(512,512)
print(MM.shape)
(512, 512)

Edit:要根据您的注释进行澄清,您传递给savez的关键字不必与对象名称匹配。我上面的操作方式应该对您有用。

© www.soinside.com 2019 - 2024. All rights reserved.