Bird
Raised Fist0
NumPydata~10 mins

Memory-mapped files with np.memmap in NumPy - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Memory-mapped files with np.memmap
Create memmap file
↓
Access data via memmap
↓
Read/Write data
↓
Changes saved to disk
↓
Close memmap file
Memory-mapped files let you work with large arrays stored on disk as if they were in memory, reading and writing parts without loading all at once.
Execution Sample
NumPy
import numpy as np
filename = 'data.dat'
# Create memmap
mmap = np.memmap(filename, dtype='float32', mode='w+', shape=(3,3))
mmap[:] = np.arange(9).reshape(3,3)
mmap.flush()
This code creates a 3x3 memory-mapped file, writes numbers 0 to 8 into it, and saves changes to disk.
Execution Table
StepActionVariable/ExpressionResult/State
1Create memmap filenp.memmap(filename, dtype='float32', mode='w+', shape=(3,3))3x3 array on disk, uninitialized
2Assign valuesmmap[:] = np.arange(9).reshape(3,3)mmap contains [[0,1,2],[3,4,5],[6,7,8]]
3Flush changesmmap.flush()Data written to 'data.dat' on disk
4Read valuemmap[1,2]5.0
5Modify valuemmap[0,0] = 100mmap updated at position (0,0)
6Flush changesmmap.flush()Changes saved to disk
7Close memmapdel mmapMemory map closed, file remains on disk
💡 Finished writing and reading data; memmap closed to release resources.
Variable Tracker
VariableStartAfter Step 2After Step 5Final
mmapempty 3x3 array on disk[[0,1,2],[3,4,5],[6,7,8]][[100,1,2],[3,4,5],[6,7,8]]same as after step 5, closed after step 7
Key Moments - 3 Insights
Why do we need to call mmap.flush() after modifying data?
Calling mmap.flush() writes changes from memory back to the disk file. Without it, changes may stay only in memory and not be saved, as shown in steps 3 and 6.
Is the entire file loaded into memory when creating a memmap?
No, memmap loads only parts of the file as needed, allowing working with large files without using much RAM. Step 1 creates the file but does not load all data.
What happens if we delete the mmap variable?
Deleting mmap closes the memory map and releases resources, but the file remains on disk with saved data, as in step 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of mmap[1,2] at step 4?
A4
B5
C2
D100
💡 Hint
Check step 4 in the execution_table where mmap[1,2] is read.
At which step does the value at position (0,0) change to 100?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look at the 'Modify value' action in the execution_table.
If we skip calling mmap.flush() after modifying data, what happens?
AChanges remain only in memory and may be lost
BFile is deleted
CChanges are saved immediately to disk
DProgram crashes
💡 Hint
Refer to key_moments about why flush() is needed.
Concept Snapshot
np.memmap(filename, dtype, mode, shape) creates a memory-mapped array.
You can read/write like a normal array.
Changes are saved to disk with flush().
Good for large data that doesn't fit in RAM.
Close or delete memmap to release resources.
Full Transcript
Memory-mapped files with np.memmap allow working with large arrays stored on disk as if they were in memory. You create a memmap object pointing to a file, then read or write data like a normal array. Changes are not saved automatically; you must call flush() to write them to disk. This method helps handle big data without loading it all into RAM. When done, delete or close the memmap to free resources. The execution steps show creating a 3x3 memmap, writing numbers, reading a value, modifying it, flushing changes, and closing the map.

Practice

(1/5)
1. What is the main benefit of using np.memmap in data science?
easy
A. It allows working with large arrays stored on disk without loading all data into memory.
B. It automatically speeds up all calculations by using GPU acceleration.
C. It compresses data files to save disk space.
D. It converts arrays into Python lists for easier manipulation.

Solution

  1. Step 1: Understand what np.memmap does

    np.memmap creates an array-like object that accesses data stored on disk instead of loading it fully into memory.
  2. Step 2: Identify the main advantage

    This allows handling very large datasets without using large amounts of RAM, which is the main benefit.
  3. Final Answer:

    It allows working with large arrays stored on disk without loading all data into memory. -> Option A
  4. Quick 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
A. np.memmap('data.dat', dtype='float64', mode='w+', shape=(100, 100))
B. np.memmap('data.dat', dtype='float32', mode='r', shape=(100, 100))
C. np.memmap('data.dat', dtype='float32', mode='rw', shape=(100, 100))
D. np.memmap('data.dat', dtype='float32', mode='w+', shape=(100, 100))

Solution

  1. Step 1: Check the mode for creating a new file

    Mode 'w+' creates a new file or overwrites existing one for reading and writing.
  2. Step 2: Verify dtype and shape parameters

    The dtype should be 'float32' and shape (100, 100) as given.
  3. Final Answer:

    np.memmap('data.dat', dtype='float32', mode='w+', shape=(100, 100)) -> Option D
  4. Quick 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
A. 6
B. 5
C. 7
D. 8

Solution

  1. 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]]
  2. Step 2: Identify the value at position [1,2]

    Row 1, column 2 is the third element in second row, which is 5.
  3. Final Answer:

    5 -> Option B
  4. Quick 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
A. File 'data.dat' does not exist, so mode 'r+' causes an error.
B. dtype 'float64' is not supported by np.memmap.
C. Shape parameter must be omitted when opening existing memmap files.
D. Mode 'r+' is read-only and cannot write to file.

Solution

  1. Step 1: Understand mode 'r+'

    Mode 'r+' opens an existing file for reading and writing. If file does not exist, it raises an error.
  2. Step 2: Check file existence

    If 'data.dat' does not exist, this code will raise a FileNotFoundError.
  3. Final Answer:

    File 'data.dat' does not exist, so mode 'r+' causes an error. -> Option A
  4. Quick 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
A. Open the file with mode='w+' and overwrite data before computing mean.
B. Load the entire file into a numpy array and then compute the mean of the first column.
C. Open the file with mode='r' and read only the first column slice to compute the mean.
D. Use np.memmap with mode='c' and compute mean on the whole array.

Solution

  1. Step 1: Understand memory constraints

    The dataset is very large (10000x10000), so loading all data into memory is inefficient.
  2. 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.
  3. 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.
  4. Final Answer:

    Open the file with mode='r' and read only the first column slice to compute the mean. -> Option C
  5. Quick 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