如何确定.npz文件的形状/大小



我有一个扩展名为.npz的文件。我怎样才能确定它的形状。我在colab上加载了这个代码

import numpy as np 
file=np.load(path/to/.npz)

我无法确定它的形状

生成样本.npz文件

import numpy as np
import zipfile

x = np.arange(10)
y = np.sin(x)
np.savez("out.npz", x, y)
def npz_headers(npz):
"""
Takes a path to an .npz file, which is a Zip archive of .npy files.
Generates a sequence of (name, shape, np.dtype).
"""
with zipfile.ZipFile(npz) as archive:
for name in archive.namelist():
if not name.endswith('.npy'):
continue
npy = archive.open(name)
version = np.lib.format.read_magic(npy)
shape, fortran, dtype = np.lib.format._read_array_header(npy, version)
yield name[:-4], shape, dtype
print(list(npz_headers("out.npz")))

调用上述函数,返回以下输出

[('arr_0', (10,), dtype('int64')), ('arr_1', (10,), dtype('float64'))]

您可以简单地遍历每个元素并查询其形状和其他信息。

# create your file
d = np.arange(10)
e = np.arange(20)
np.savez("mat",x = d, y = e)
#load it
data = np.load("mat.npz")
for key in data.keys():
print("variable name:", key          , end="  ")
print("type: "+ str(data[key].dtype) , end="  ")
print("shape:"+ str(data[key].shape))

输出:

variable name: x  type: int32  shape:(10,)
variable name: y  type: int32  shape:(20,)

最新更新