【问题标题】:Fast access to numpy npz data快速访问 numpy npz 数据
【发布时间】:2015-08-04 00:01:58
【问题描述】:

我已将许多数据文件保存为 .npz 以节省存储空间 (savez_compressed)。每个文件都保存为一个数组,因此在使用 numpy load 函数时,它会将键返回到包含该数组的字典。

如何快速将此数组存储为数组而不是字典。

例如:

data = []
datum = np.load('file.npz')
key = datum.keys()[0]
data.append([datum[key]])

在对此进行分析时,我的代码大部分时间都在使用字典的 get 方法。

如果保存为 .npz 文件,则不需要get 方法,速度更快。

data = []
data.append([np.load('file.npz')])

我认为通过加载文件,这两种情况下数据都已经在内存中了。 savez_compressed 似乎没有保存为数组的选项。这是可能的还是有办法加快加载速度?

【问题讨论】:

    标签: python numpy npz-file


    【解决方案1】:

    np.load 使用np.lib.npyio.NpzFile 类加载npz 文件。它的文档是:

    NpzFile(fid)
    
    A dictionary-like object with lazy-loading of files in the zipped
    archive provided on construction.
    
    `NpzFile` is used to load files in the NumPy ``.npz`` data archive
    format. It assumes that files in the archive have a ".npy" extension,
    other files are ignored.
    
    The arrays and file strings are lazily loaded on either
    getitem access using ``obj['key']`` or attribute lookup using
    ``obj.f.key``. A list of all files (without ".npy" extensions) can
    be obtained with ``obj.files`` and the ZipFile object itself using
    ``obj.zip``.
    

    我认为最后一段回答了您的时间问题。在您执行字典 get 之前不会加载数据。所以它不仅仅是内存中的字典查找 - 它是文件加载(解压缩)。

    Python 字典查找速度很快——解释器在访问对象属性时一直在做。以及在简单地管理命名空间时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多