Python 查找保存的numpy数组(.npy或.npz)的形状而不加载到内存中
我有一个巨大的压缩numpy阵列保存到磁盘上(内存约20gb,压缩时要少得多)。我需要知道这个数组的形状,但是我没有可用的内存来加载它。如何在不将numpy数组加载到内存的情况下找到它的形状?在Python 查找保存的numpy数组(.npy或.npz)的形状而不加载到内存中,python,numpy,io,Python,Numpy,Io,我有一个巨大的压缩numpy阵列保存到磁盘上(内存约20gb,压缩时要少得多)。我需要知道这个数组的形状,但是我没有可用的内存来加载它。如何在不将numpy数组加载到内存的情况下找到它的形状?在mmap\u模式下打开该文件可能会奏效 也可以在不读取数据缓冲区的情况下读取头块,但这需要进一步深入底层lib/npyio/formatcode。我在最近一个关于在一个文件中存储多个数组(并读取它们)的问题中探讨了这一点 这样做: import numpy as np import zipfile de
mmap\u模式下打开该文件可能会奏效
也可以在不读取数据缓冲区的情况下读取头块,但这需要进一步深入底层lib/npyio/format
code。我在最近一个关于在一个文件中存储多个数组(并读取它们)的问题中探讨了这一点
这样做:
import numpy as np
import zipfile
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
这适用于.npy,但不适用于.npz。我认为mmap对.npz一点用处都没有——如果数据是压缩的,也就是np.savez_compressed()
。在npz
存档中执行任何操作都需要深入到加载程序的分支np.lib.npyio.NpzFile
。关键文件格式信息确实在np.lib.npyio.format
中。我已经在这里的答案中实现了它。这个答案是完美的,应该是公认的答案。。。
import numpy as np
import zipfile
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