我有一个矩阵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'
[就像评论说的那样,您永远不会告诉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
的关键字不必与对象名称匹配。我上面的操作方式应该对您有用。