0
0
NumPydata~10 mins

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

Choose your learning style9 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.