How to determine the shape/size of .npz file

Viewed 788

I have a file with .npz extension. How can I determine its shape. I loaded it on colab with this code

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

I am unable to determine its shape

2 Answers

Generating Sample .npz file

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")))

Calling the above function, it returns the below output

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

You can simply iterate through each element and query its shape and other info.

# 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))

output:

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