Memory-mapped files let you work with big data stored on disk as if it were in memory. This helps when your data is too large to fit in your computer's RAM.
Memory-mapped files with np.memmap in NumPy
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NumPy
np.memmap(filename, dtype='float32', mode='r+', offset=0, shape=None, order='C')
filename is the path to the binary file on disk.
mode controls read/write access: 'r' for read-only, 'r+' for read-write, 'w+' to create or overwrite.
Examples
NumPy
import numpy as np # Open existing file for reading mmap_array = np.memmap('data.dat', dtype='float32', mode='r', shape=(1000, 1000))
NumPy
import numpy as np # Create a new memmap file and write data mmap_array = np.memmap('new_data.dat', dtype='int32', mode='w+', shape=(500, 500)) mmap_array[:] = np.arange(250000).reshape(500, 500) mmap_array.flush()
Sample Program
This program creates a memory-mapped file, writes a 3x4 array to it, saves it, then reads it back and prints the array.
NumPy
import numpy as np # Create a memmap file with shape (3, 4) and int32 data filename = 'example.dat' mmap_array = np.memmap(filename, dtype='int32', mode='w+', shape=(3, 4)) # Fill the array with values mmap_array[:] = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Save changes to disk mmap_array.flush() # Open the same file for reading mmap_read = np.memmap(filename, dtype='int32', mode='r', shape=(3, 4)) # Print the data read from the file print(mmap_read)
Important Notes
Always call flush() to save changes from memory to disk.
Memory-mapped files work best with binary data, not text files.
Be careful with the shape and dtype to match the file's data layout.
Summary
Memory-mapped files let you handle large data on disk like arrays in memory.
Use np.memmap to create or open these files with control over reading and writing.
This helps save memory and speeds up working with big datasets.
Practice
1. What is the main benefit of using
np.memmap in data science?easy
Solution
Step 1: Understand what
np.memmapdoesnp.memmapcreates an array-like object that accesses data stored on disk instead of loading it fully into memory.Step 2: Identify the main advantage
This allows handling very large datasets without using large amounts of RAM, which is the main benefit.Final Answer:
It allows working with large arrays stored on disk without loading all data into memory. -> Option AQuick Check:
Memory-mapped files save RAM by accessing disk data [OK]
Hint: Remember: memmap works with disk data like memory arrays [OK]
Common Mistakes:
- Thinking memmap compresses data
- Assuming memmap loads all data into RAM
- Confusing memmap with GPU acceleration
2. Which of the following is the correct way to create a new memory-mapped file with
np.memmap of shape (100, 100) and dtype float32?easy
Solution
Step 1: Check the mode for creating a new file
Mode 'w+' creates a new file or overwrites existing one for reading and writing.Step 2: Verify dtype and shape parameters
The dtype should be 'float32' and shape (100, 100) as given.Final Answer:
np.memmap('data.dat', dtype='float32', mode='w+', shape=(100, 100)) -> Option DQuick Check:
Use mode='w+' to create new memmap files [OK]
Hint: Use mode='w+' to create or overwrite memmap files [OK]
Common Mistakes:
- Using mode='r' when creating a new file
- Using incorrect dtype like float64 instead of float32
- Using invalid mode 'rw' which does not exist
3. What will be the output of this code snippet?
import numpy as np filename = 'test.dat' # Create memmap file fp = np.memmap(filename, dtype='int32', mode='w+', shape=(3,3)) fp[:] = np.arange(9).reshape(3,3) fp.flush() # Open memmap file in read mode fp2 = np.memmap(filename, dtype='int32', mode='r', shape=(3,3)) print(fp2[1,2])
medium
Solution
Step 1: Understand the array content
np.arange(9).reshape(3,3) creates a 3x3 array: [[0,1,2],[3,4,5],[6,7,8]]Step 2: Identify the value at position [1,2]
Row 1, column 2 is the third element in second row, which is 5.Final Answer:
5 -> Option BQuick Check:
Index [1,2] in arange(9).reshape(3,3) = 5 [OK]
Hint: Remember zero-based indexing for rows and columns [OK]
Common Mistakes:
- Confusing row and column indices
- Forgetting zero-based indexing
- Assuming flush() changes data values
4. Identify the error in this code snippet that tries to open a memmap file:
import numpy as np filename = 'data.dat' # Attempt to open memmap file fp = np.memmap(filename, dtype='float64', mode='r+', shape=(10,10)) print(fp[0,0])
medium
Solution
Step 1: Understand mode 'r+'
Mode 'r+' opens an existing file for reading and writing. If file does not exist, it raises an error.Step 2: Check file existence
If 'data.dat' does not exist, this code will raise a FileNotFoundError.Final Answer:
File 'data.dat' does not exist, so mode 'r+' causes an error. -> Option AQuick Check:
Mode 'r+' requires existing file [OK]
Hint: Use mode='w+' to create files, 'r+' needs existing file [OK]
Common Mistakes:
- Assuming 'r+' creates new files
- Thinking dtype 'float64' is invalid
- Believing shape must be omitted always
5. You have a very large dataset stored in a binary file 'large_data.dat' with shape (10000, 10000) and dtype float64. You want to compute the mean of the first column without loading the entire file into memory. Which approach using
np.memmap is best?hard
Solution
Step 1: Understand memory constraints
The dataset is very large (10000x10000), so loading all data into memory is inefficient.Step 2: Use memmap to read only needed data
Opening with mode='r' allows read-only access. Slicing the first column reads only that part from disk, saving memory.Step 3: Avoid unnecessary writes or full reads
Mode 'w+' overwrites data, which is not desired. Mode 'c' is copy-on-write and still loads data. Loading full array wastes memory.Final Answer:
Open the file with mode='r' and read only the first column slice to compute the mean. -> Option CQuick Check:
Read-only memmap + slice = efficient mean calculation [OK]
Hint: Read only needed slices with mode='r' to save memory [OK]
Common Mistakes:
- Loading entire large file into memory
- Using mode='w+' which overwrites data
- Not slicing and reading whole array unnecessarily
