Bird
Raised Fist0
NumPydata~10 mins

Type casting with astype() in NumPy - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Type casting with astype()
Start with numpy array
↓
Call astype() with target type
↓
Create new array with new type
↓
Use new array for further work
↓
End
We start with a numpy array, call astype() to convert it to a new type, which creates a new array with that type for further use.
Execution Sample
NumPy
import numpy as np
arr = np.array([1.5, 2.3, 3.7])
new_arr = arr.astype(int)
print(new_arr)
This code converts a float array to an integer array by dropping decimals.
Execution Table
StepActionInput ArrayTarget TypeOutput Array
1Create original array[1.5, 2.3, 3.7]float64 (default)[1.5, 2.3, 3.7]
2Call astype(int)[1.5, 2.3, 3.7]int[1, 2, 3]
3Print new array[1, 2, 3]int[1, 2, 3]
4End---
💡 Finished converting float array to int array and printed result.
Variable Tracker
VariableStartAfter astype() callFinal
arr[1.5, 2.3, 3.7][1.5, 2.3, 3.7][1.5, 2.3, 3.7]
new_arrN/A[1, 2, 3][1, 2, 3]
Key Moments - 2 Insights
Why does the original array 'arr' not change after calling astype()?
astype() creates a new array with the new type and does not modify the original array, as shown in execution_table step 2 and variable_tracker.
What happens to the decimal parts when converting floats to integers with astype()?
The decimal parts are dropped (truncated), not rounded. For example, 1.5 becomes 1, as seen in the output array in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 2. What is the output array after calling astype(int)?
A[1, 2, 3]
B[1.5, 2.3, 3.7]
C[2, 3, 4]
D[1, 3, 4]
💡 Hint
Check the 'Output Array' column at step 2 in the execution_table.
At which step does the original array 'arr' remain unchanged?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at variable_tracker for 'arr' values after astype() call.
If we changed astype(int) to astype(str), what would the output array look like?
AArray of integers like [1, 2, 3]
BArray of strings like ['1.5', '2.3', '3.7']
CArray of floats like [1.5, 2.3, 3.7]
DError because str is invalid
💡 Hint
astype() can convert to string type, converting each element to its string form.
Concept Snapshot
astype() converts a numpy array to a new type.
It returns a new array; original stays unchanged.
Decimals are truncated when converting float to int.
Syntax: new_arr = arr.astype(new_type)
Common types: int, float, str.
Full Transcript
We start with a numpy array of floats. Calling astype(int) creates a new array where each float is converted to an integer by dropping the decimal part. The original array remains unchanged. The new array can then be used for further processing. This process is shown step-by-step in the execution table and variable tracker.

Practice

(1/5)
1. What does the astype() method do in NumPy?
easy
A. It changes the data type of a NumPy array and returns a new array.
B. It sorts the elements of a NumPy array in ascending order.
C. It removes duplicate elements from a NumPy array.
D. It reshapes the NumPy array into a new shape.

Solution

  1. Step 1: Understand the purpose of astype()

    The astype() method is used to convert the data type of elements in a NumPy array.
  2. Step 2: Recall the behavior of astype()

    It returns a new array with the changed data type and does not modify the original array.
  3. Final Answer:

    It changes the data type of a NumPy array and returns a new array. -> Option A
  4. Quick Check:

    astype() changes type and returns new array [OK]
Hint: Remember: astype() changes type and returns a new array [OK]
Common Mistakes:
  • Thinking astype() modifies the original array in place
  • Confusing astype() with sorting or reshaping functions
  • Assuming astype() removes duplicates
2. Which of the following is the correct syntax to convert a NumPy array arr to float type using astype()?
easy
A. arr.convert(float)
B. astype(arr, float)
C. arr.to_float()
D. arr.astype(float)

Solution

  1. Step 1: Recall the method call syntax for astype()

    The astype() method is called on the array object like arr.astype().
  2. Step 2: Check the argument for data type

    The argument should be the desired data type, here float, passed inside parentheses.
  3. Final Answer:

    arr.astype(float) -> Option D
  4. Quick Check:

    Correct syntax is arr.astype(type) [OK]
Hint: Call astype() on array with desired type inside parentheses [OK]
Common Mistakes:
  • Using astype as a standalone function instead of a method
  • Using incorrect method names like convert or to_float
  • Passing data type outside parentheses
3. What will be the output of the following code?
import numpy as np
arr = np.array([1.7, 2.3, 3.9])
new_arr = arr.astype(int)
print(new_arr)
medium
A. [2 3 4]
B. [1.7 2.3 3.9]
C. [1 2 3]
D. Error: Cannot convert float to int

Solution

  1. Step 1: Understand astype(int) on float array

    Converting floats to int using astype(int) truncates the decimal part (does not round).
  2. Step 2: Apply truncation to each element

    1.7 becomes 1, 2.3 becomes 2, 3.9 becomes 3.
  3. Final Answer:

    [1 2 3] -> Option C
  4. Quick Check:

    astype(int) truncates floats to integers [OK]
Hint: astype(int) truncates decimals, does not round [OK]
Common Mistakes:
  • Assuming astype(int) rounds instead of truncates
  • Expecting original array to change
  • Thinking conversion causes error
4. Identify the error in the following code snippet:
import numpy as np
arr = np.array([1, 2, 3])
new_arr = arr.astype('int32')
print(new_arr.astype('float64'))
medium
A. Error because 'int32' is not a valid dtype string
B. No error; code runs and prints float64 array
C. Error because astype() cannot be chained
D. Error because original array is modified

Solution

  1. Step 1: Check dtype string validity

    'int32' and 'float64' are valid NumPy dtype strings for 32-bit int and 64-bit float.
  2. Step 2: Verify chaining of astype()

    Chaining astype() calls is allowed because each returns a new array.
  3. Final Answer:

    No error; code runs and prints float64 array -> Option B
  4. Quick Check:

    Valid dtype strings and chaining astype() work [OK]
Hint: astype() returns new array; chaining is allowed [OK]
Common Mistakes:
  • Thinking dtype strings like 'int32' are invalid
  • Believing astype() modifies original array
  • Assuming astype() cannot be chained
5. You have a NumPy array arr = np.array([10, 20, 30]) of integers. You want to save memory by converting it to the smallest unsigned integer type that can hold these values. Which astype() call is best?
hard
A. arr.astype('uint8')
B. arr.astype('int8')
C. arr.astype('float16')
D. arr.astype('uint16')

Solution

  1. Step 1: Check the range of values in arr

    Values are 10, 20, 30, all positive and less than 255.
  2. Step 2: Choose smallest unsigned integer type

    uint8 holds values 0 to 255, so it fits all values and saves memory.
  3. Step 3: Compare with other options

    int8 supports -128 to 127 but is signed; float16 uses more memory; uint16 is larger than needed.
  4. Final Answer:

    arr.astype('uint8') -> Option A
  5. Quick Check:

    Use smallest unsigned int type fitting data [OK]
Hint: Pick smallest unsigned int type covering max value [OK]
Common Mistakes:
  • Choosing signed int type that wastes range or causes errors
  • Using float type which uses more memory
  • Ignoring value ranges when selecting dtype
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard