0
0
Pandasdata~10 mins

astype() for type conversion in Pandas - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - astype() for type conversion
Start with DataFrame
Call astype() with target type
pandas converts each column to new type
Return new DataFrame with converted types
Use or display converted DataFrame
The astype() method converts DataFrame columns to a specified data type and returns a new DataFrame with those types.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({'A': ['1', '2', '3'], 'B': ['4.5', '5.5', '6.5']})
df2 = df.astype({'A': 'int', 'B': 'float'})
print(df2)
This code converts column 'A' from string to int and column 'B' from string to float.
Execution Table
StepActionInput Data TypesConversion TargetOutput Data TypesResult
1Create DataFrame{'A': ['1', '2', '3'], 'B': ['4.5', '5.5', '6.5']}N/A{'A': object (string), 'B': object (string)}DataFrame with string columns
2Call astype() with {'A': 'int', 'B': 'float'}{'A': object, 'B': object}{'A': int, 'B': float}N/AStart conversion
3Convert column 'A' to int['1', '2', '3']int[1, 2, 3]Success
4Convert column 'B' to float['4.5', '5.5', '6.5']float[4.5, 5.5, 6.5]Success
5Return new DataFrameN/AN/A{'A': int64, 'B': float64}DataFrame with converted types
6Print df2N/AN/AN/AOutput: A B 0 1 4.5 1 2 5.5 2 3 6.5
💡 All columns converted successfully, astype() returns new DataFrame with specified types.
Variable Tracker
VariableStartAfter astype() callFinal
df['A']['1', '2', '3'] (string)['1', '2', '3'] (string)['1', '2', '3'] (string)
df['B']['4.5', '5.5', '6.5'] (string)['4.5', '5.5', '6.5'] (string)['4.5', '5.5', '6.5'] (string)
df2N/ADataFrame with converted typesDataFrame with converted types
Key Moments - 3 Insights
Why does astype() return a new DataFrame instead of changing the original?
astype() creates a new DataFrame to avoid modifying the original data unexpectedly. See execution_table step 5 where the new DataFrame is returned.
What happens if a value cannot be converted to the target type?
astype() will raise an error if conversion fails. In this example, all values convert successfully (steps 3 and 4).
Can astype() convert multiple columns at once?
Yes, by passing a dictionary with column names and target types as in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the output of converting column 'A'?
A[4.5, 5.5, 6.5] as floats
B[1, 2, 3] as integers
C['1', '2', '3'] as strings
DConversion error
💡 Hint
Check the 'Output Data Types' and 'Result' columns at step 3 in execution_table.
At which step does astype() return the new DataFrame with converted types?
AStep 5
BStep 2
CStep 4
DStep 6
💡 Hint
Look for the step mentioning 'Return new DataFrame' in execution_table.
If column 'B' had a non-numeric string, what would happen during conversion at step 4?
AIt would convert to zero
BIt would convert to NaN silently
Castype() would raise an error
DIt would convert to string type
💡 Hint
Recall key_moments about conversion errors and check step 4's 'Result' column.
Concept Snapshot
astype() converts DataFrame columns to specified types.
Pass a dict with column names and target types.
Returns a new DataFrame; original stays unchanged.
Raises error if conversion fails.
Useful for cleaning and preparing data.
Full Transcript
We start with a DataFrame where columns 'A' and 'B' contain strings. Using astype(), we specify that 'A' should become integers and 'B' floats. The method converts each column step-by-step, creating a new DataFrame with the new types. The original DataFrame remains unchanged. If any value cannot convert, astype() raises an error. This method is helpful to prepare data for analysis by ensuring correct data types.