0
0
NumPydata~20 mins

Type casting with astype() in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Casting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[1, 2, 3]
B[1 2 3]
C[1.0 2.0 3.0]
D[1. 2. 3.]
Attempts:
2 left
💡 Hint
astype(float) converts integers to floating point numbers with decimal points.
data_output
intermediate
2: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)
Afloat64
Bint64
Cint32
Dobject
Attempts:
2 left
💡 Hint
astype(int) converts floats to integers by truncating decimals.
🔧 Debug
advanced
2: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)
ATypeError: unsupported operand type(s) for astype
BSyntaxError: invalid syntax
CValueError: invalid literal for int() with base 10: 'three'
DNo error, outputs array([1, 2, 0])
Attempts:
2 left
💡 Hint
The string 'three' cannot be converted to an integer.
🚀 Application
advanced
2: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?
Aarr.astype(np.uint8)
Barr.astype(np.float64)
Carr.astype(np.int64)
Darr.astype(str)
Attempts:
2 left
💡 Hint
Values between 0 and 255 fit in an 8-bit unsigned integer.
🧠 Conceptual
expert
2:00remaining
Effect of astype() on array views and copies
Which statement about astype() is true?
Aastype() always returns a new array copy with the requested type.
Bastype() modifies the original array in place without copying.
Castype() returns a view of the original array with changed dtype.
Dastype() changes the dtype of the original array without copying.
Attempts:
2 left
💡 Hint
astype() creates a new array even if the dtype is the same.