If you don't specify dtype, numpy guesses the type based on data.
Choosing the right dtype can save memory and speed up your program.
For strings, 'U' means Unicode and the number after it is max length.
Summary
Use dtype to control the type of data stored in numpy arrays.
Specifying dtype helps with memory and performance.
Common dtypes include int, float, bool, and string (Unicode).
Practice
(1/5)
1. What does specifying dtype when creating a NumPy array do?
easy
A. It sets the type of data stored in the array.
B. It changes the shape of the array.
C. It sorts the array elements.
D. It deletes elements from the array.
Solution
Step 1: Understand the role of dtype in NumPy
The dtype parameter defines the type of data (like int, float) stored in the array.
Step 2: Compare with other options
Changing shape, sorting, or deleting elements are unrelated to dtype.
Final Answer:
It sets the type of data stored in the array. -> Option A
Quick Check:
dtype controls data type = A [OK]
Hint: dtype controls data type stored in array [OK]
Common Mistakes:
Confusing dtype with array shape
Thinking dtype sorts or deletes elements
Assuming dtype changes array size
2. Which of the following is the correct way to create a NumPy array of integers using dtype?
easy
A. np.array([1, 2, 3], type='int')
B. np.array([1, 2, 3], dtype='int')
C. np.array([1, 2, 3], dtype=int32)
D. np.array([1, 2, 3], dtype='string')
Solution
Step 1: Check correct dtype syntax
The correct parameter is dtype with a string like 'int' or a NumPy dtype like np.int32.
Step 2: Evaluate each option
np.array([1, 2, 3], dtype='int') uses dtype='int' which is valid. np.array([1, 2, 3], type='int') uses wrong parameter type. np.array([1, 2, 3], dtype=int32) uses dtype=int32 without quotes or np.int32, which causes error. np.array([1, 2, 3], dtype='string') uses dtype='string' which is valid but not integer.
Final Answer:
np.array([1, 2, 3], dtype='int') -> Option B
Quick Check:
Correct dtype syntax = A [OK]
Hint: Use dtype='int' or dtype=np.int32 for integers [OK]
Common Mistakes:
Using 'type' instead of 'dtype'
Missing quotes around dtype string
Using wrong dtype names like 'string' for integers