Here's an approach to load NumPy arrays from .npz files efficiently while managing memory:
import numpy as np
class LazyNumpyLoader:
def __init__(self, npz_file):
self.npz_file = npz_file
self.file = np.load(self.npz_file, allow_pickle=True)
self.keys = list(self.file.keys())
def __del__(self):
self.file.close()
def get_array(self, key):
# Load specific array into memory
array = self.file[key][()] # Use [()] to handle pickled objects if needed
return array
def list_keys(self):
return self.keys
# Usage example
def process_array(array):
# Do something with the array
result = array * 2
return result
# Create lazy loaders for multiple files
loaders = [
LazyNumpyLoader('file1.npz'),
LazyNumpyLoader('file2.npz')
]
# Load and process arrays on-demand
for loader in loaders:
for key in loader.list_keys():
# Load array only when needed
array = loader.get_array(key)
# Process the array
processed_result = process_array(array)
# Array will be automatically garbage collected after use
del array
Key points in this approach:
-
LazyNumpyLoader class allows you to:
- Open .npz files without loading all arrays into memory
- List available array keys
- Load specific arrays on-demand
- Automatically close the file when done
-
get_array() method loads only the requested array into memory
-
del array ensures the array is removed from memory after processing
-
The __del__ method ensures the .npz file is properly closed
Alternative approach using numpy.load() with allow_pickle=True:
import numpy as np
def process_npz_file(filename):
with np.load(filename, allow_pickle=True) as data:
for key in data.keys():
array = data[key][()] # Load specific array
# Process the array
processed_result = process_array(array)
# Array will be garbage collected when exiting the with block
Memory-efficient tips:
- Use
del to remove large arrays from memory
- Work with arrays in chunks if possible
- Consider using memory-mapped files for very large datasets
- Monitor memory usage with
memory_profiler or system tools
If you're dealing with extremely large datasets, you might also want to explore:
- Dask for out-of-core computing
- Memory-mapped NumPy arrays
- HDF5 with
h5py for large dataset management