Search code examples
pythonnumpysizegoogle-colaboratoryshapes

How to determine the shape/size of .npz file


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


Solution

  • 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'))]