0
0
NumPydata~10 mins

Memory-mapped arrays for large data in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a memory-mapped array from a file.

NumPy
import numpy as np
mmap_array = np.memmap('data.dat', dtype='float32', mode=[1], shape=(1000, 1000))
Drag options to blanks, or click blank then click option'
A'r'
B'w+'
C'r+'
D'c'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w+' mode when the file does not exist causes an error.
Using 'r+' mode without write permission causes an error.
2fill in blank
medium

Complete the code to write data to a new memory-mapped file.

NumPy
import numpy as np
mmap_array = np.memmap('new_data.dat', dtype='int32', mode=[1], shape=(500, 500))
mmap_array[:] = np.arange(250000).reshape(500, 500)
mmap_array.flush()
Drag options to blanks, or click blank then click option'
A'r+'
B'r'
C'c'
D'w+'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode which does not allow writing.
Using 'r+' mode without an existing file.
3fill in blank
hard

Fix the error in the code to correctly access the memory-mapped array slice.

NumPy
import numpy as np
mmap_array = np.memmap('data.dat', dtype='float64', mode='r', shape=(100, 100))
slice_data = mmap_array[[1]]
Drag options to blanks, or click blank then click option'
A[50:60]
B50:60
C(50:60)
D50, 60
Attempts:
3 left
💡 Hint
Common Mistakes
Using commas inside the brackets which is invalid for slicing.
Adding extra brackets around the slice.
4fill in blank
hard

Fill both blanks to create a memory-mapped array and then read a specific element.

NumPy
import numpy as np
mmap_array = np.memmap('file.dat', dtype=[1], mode='r', shape=(10, 10))
element = mmap_array[[2]]
Drag options to blanks, or click blank then click option'
A'float64'
B5, 5
C7, 3
D'int32'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a tuple for dtype instead of a string.
Using a single index instead of two for a 2D array.
5fill in blank
hard

Fill all three blanks to create a writable memory-mapped array, modify it, and save changes.

NumPy
import numpy as np
mmap_array = np.memmap('mod_data.dat', dtype=[1], mode=[2], shape=(20, 20))
mmap_array[10, 10] = [3]
mmap_array.flush()
Drag options to blanks, or click blank then click option'
A'float32'
B'r+'
C42.0
D'r'
Attempts:
3 left
💡 Hint
Common Mistakes
Using mode 'r' which does not allow writing.
Assigning a value without matching dtype.