0
0
NumPydata~10 mins

Why dtypes matter for performance in NumPy - Test Your Understanding

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

Complete the code to create a NumPy array with integer data type.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4], dtype=[1])
print(arr.dtype)
Drag options to blanks, or click blank then click option'
Abool
Bfloat64
Cstr
Dint32
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'float64' when integers are needed.
Using 'str' which is for text data.
2fill in blank
medium

Complete the code to create a NumPy array of floats for better precision.

NumPy
import numpy as np
arr = np.array([1.0, 2.5, 3.1], dtype=[1])
print(arr.dtype)
Drag options to blanks, or click blank then click option'
Aint64
Bbool
Cfloat64
Dint32
Attempts:
3 left
💡 Hint
Common Mistakes
Using integer types for decimal numbers causes truncation.
Using boolean type which only stores True or False.
3fill in blank
hard

Fix the error in the code by choosing the correct dtype for a boolean array.

NumPy
import numpy as np
arr = np.array([True, False, True], dtype=[1])
print(arr.dtype)
Drag options to blanks, or click blank then click option'
Abool
Bfloat64
Cint32
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using integer or float types wastes memory for boolean data.
Using string type causes errors when printing dtype.
4fill in blank
hard

Fill both blanks to create a NumPy array of integers and convert it to float for better precision.

NumPy
import numpy as np
arr = np.array([1, 2, 3], dtype=[1])
arr_float = arr.astype([2])
print(arr_float.dtype)
Drag options to blanks, or click blank then click option'
Aint32
Bfloat64
Cint64
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using boolean dtype initially causes wrong data representation.
Converting to integer instead of float loses decimal precision.
5fill in blank
hard

Fill both blanks to create a float array, check its size, and convert it to int to save memory.

NumPy
import numpy as np
arr = np.array([1.5, 2.3, 3.7], dtype=[1])
print(arr.nbytes)
arr_int = arr.astype([2])
print(arr_int.nbytes)
print(arr_int)
Drag options to blanks, or click blank then click option'
Afloat64
Bint32
Cfloat32
Dint64
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same dtype for both arrays does not change memory usage.
Converting to float instead of int does not reduce memory.