Skip to main content
 首页 » 编程设计

python之是否可以使用 h5py 将大数据直接加载到 numpy int8 数组中

2024年10月01日32leader

我有一个非常大的数据文件(1000 x 1400000 数组),其中包含整数 0、1、2 和 4。使用 h5py 将这个大数据加载到 numpy 数组需要很长时间,因为我的内存(4GB ) 不能容纳那么多,程序使用交换空间。由于数据中只有 4 个数字,我想使用一个 8 位整数数组。目前我加载数据并将其转换为 8 位 int 数组。

with h5py.File("largedata", 'r') as f: 
 
    variables = f.items() 
    # extract all data 
    for name, data in variables: 
        # If DataSet pull the associated Data 
        if type(data) is h5py.Dataset: 
            value = data.value 
            if(name == 'foo'): 
                # convert to 8 bit int 
                nparray = np.array(value, dtype=np.int8) 

加载时是否可以将数据直接加载到8bit int数组中以节省内存?

请您参考如下方法:

来自数据集文档页面

 astype(dtype) 
 
 Return a context manager allowing you to read data as a particular type.  
 Conversion is handled by HDF5 directly, on the fly: 
 
>>> dset = f.create_dataset("bigint", (1000,), dtype='int64')  
>>> with dset.astype('int16'):  
      out = dset[:]  
>>> out.dtype  
       =dtype('int16')