如何在python中部分加载用numpy保存的数组

时间:2015-12-31 03:23:23

标签: python numpy scipy

我有一个带有numpy save的多维数组,只想部分加载一些维度,因为数组非常大。

我怎样才能以简单的方式做到?

编辑:上下文简单而基本:

您使用numpy.save保存了5个Gb阵列。但是,您只需要访问数组A[:,:]的某些部分而无需在内存中加载5gb。

答案是:使用h5py部分保存/加载数据:此处代码示例:

import sys
import h5py

  def main():
data = read()

if sys.argv[1] == 'x':
    x_slice(data)
elif sys.argv[1] == 'z':
    z_slice(data)

def read():
f = h5py.File('/tmp/test.hdf5', 'r')
return f['seismic_volume']

 def z_slice(data):
return data[:,:,0]

  def x_slice(data):
return data[0,:,:]

1 个答案:

答案 0 :(得分:5)

您必须有意保存数组以进行部分加载;你不可能做到一般。

例如,您可以拆分数组(沿着其中一个维度)并使用savez保存子数组。 load这样的文件档案是“懒惰的”,只读取您要求的子文件。

h5py是一个附加软件包,用于保存和加载HDF5文件中的数据。这允许部分读取。

numpy.memmap是另一种选择,将文件视为存储数组的内存。

查看这些文档,以及之前的SO问题。

How can I efficiently read and write files that are too large to fit in memory?

Fastest save and load options for a numpy array

Writing a large hdf5 dataset using h5py

详细说明搁置。有一些小问题尚不清楚。究竟是什么意思“加载一些维度&#39 ;?最简单的解释是您需要A[0,...]A[3:10,...]。另一个是“简单方式”的含义。这是否意味着你已经拥有了一种复杂的方式,而这更简单了?或者只是你不想重写numpy.load函数来执行任务?

否则我认为问题相当清楚 - 简单的答案是 - 没有一个简单的方法。

我很想重新开启这个问题,以便其他经验丰富的numpy张海报可以权衡。

我应该查看load文档(OP应该也有!)。正如ali_m所述,存在一种内存映射模式。文档说:

  

mmap_mode:{无,' r +',' r',' w +',' c'},可选

   If not None, then memory-map the file, using the given mode
    (see `numpy.memmap` for a detailed description of the modes).
    A memory-mapped array is kept on disk. However, it can be accessed
    and sliced like any ndarray.  Memory mapping is especially useful for
    accessing small fragments of large files without reading the entire
    file into memory.

How does numpy handle mmap's over npz files? (我在几个月前挖了这个,但忘记了选项。)

Python memory mapping