Challenge - 5 Problems
Type Casting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of type casting a NumPy array to float
What is the output of this code snippet?
import numpy as np arr = np.array([1, 2, 3]) new_arr = arr.astype(float) print(new_arr)
NumPy
import numpy as np arr = np.array([1, 2, 3]) new_arr = arr.astype(float) print(new_arr)
Attempts:
2 left
💡 Hint
astype(float) converts integers to floating point numbers with decimal points.
✗ Incorrect
The astype(float) method converts the integer array elements to floats, which print with a decimal point but no trailing zeros after the decimal.
❓ data_output
intermediate2:00remaining
Resulting dtype after type casting
After running this code, what is the dtype of the new array?
import numpy as np arr = np.array([1.5, 2.5, 3.5]) new_arr = arr.astype(int) print(new_arr.dtype)
NumPy
import numpy as np arr = np.array([1.5, 2.5, 3.5]) new_arr = arr.astype(int) print(new_arr.dtype)
Attempts:
2 left
💡 Hint
astype(int) converts floats to integers by truncating decimals.
✗ Incorrect
The default integer type on most 64-bit systems is int64, so astype(int) converts to int64 dtype.
🔧 Debug
advanced2:00remaining
Identify the error in type casting code
What error does this code raise?
import numpy as np arr = np.array(['1', '2', 'three']) new_arr = arr.astype(int)
NumPy
import numpy as np arr = np.array(['1', '2', 'three']) new_arr = arr.astype(int)
Attempts:
2 left
💡 Hint
The string 'three' cannot be converted to an integer.
✗ Incorrect
astype(int) tries to convert each string to int. 'three' is not a valid integer string, so it raises ValueError.
🚀 Application
advanced2:00remaining
Using astype() to optimize memory usage
You have a large NumPy array of floats with values between 0 and 255. Which astype() conversion will reduce memory usage without losing information?
Attempts:
2 left
💡 Hint
Values between 0 and 255 fit in an 8-bit unsigned integer.
✗ Incorrect
Converting to np.uint8 uses 1 byte per element, reducing memory compared to float64 (8 bytes).
🧠 Conceptual
expert2:00remaining
Effect of astype() on array views and copies
Which statement about astype() is true?
Attempts:
2 left
💡 Hint
astype() creates a new array even if the dtype is the same.
✗ Incorrect
astype() always returns a new array copy with the requested type; it does not modify the original array or return a view.