Challenge - 5 Problems
astype() Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of astype() converting float to int
What is the output DataFrame after converting the 'score' column from float to int using astype()?
Pandas
import pandas as pd df = pd.DataFrame({'score': [95.7, 88.2, 76.9]}) df['score'] = df['score'].astype(int) print(df)
Attempts:
2 left
💡 Hint
astype(int) truncates the decimal part without rounding.
✗ Incorrect
When converting float to int with astype(), pandas truncates decimals, so 95.7 becomes 95, not rounded.
❓ data_output
intermediate2:00remaining
Resulting dtypes after astype() conversion
After running the code below, what are the data types of the columns in the DataFrame?
Pandas
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3.5, 4.5]}) df = df.astype({'A': 'float64', 'B': 'int32'}) print(df.dtypes)
Attempts:
2 left
💡 Hint
Check the specified types in the astype dictionary.
✗ Incorrect
Column 'A' is converted to float64 and 'B' to int32 as specified in astype().
🔧 Debug
advanced2:00remaining
Identify the error when converting string to numeric
What error will this code raise when trying to convert the 'age' column to int using astype()?
Pandas
import pandas as pd df = pd.DataFrame({'age': ['25', 'thirty', '40']}) df['age'] = df['age'].astype(int)
Attempts:
2 left
💡 Hint
Check if all strings can be converted to int.
✗ Incorrect
The string 'thirty' cannot be converted to int, causing a ValueError.
🚀 Application
advanced2:00remaining
Using astype() to optimize memory usage
Given a DataFrame with a column 'flag' containing only 0 and 1 as integers, which astype() conversion reduces memory usage most effectively?
Pandas
import pandas as pd df = pd.DataFrame({'flag': [0, 1, 1, 0, 0]})
Attempts:
2 left
💡 Hint
Boolean type uses less memory than integer types.
✗ Incorrect
Converting to bool uses less memory than int64 or float32 for binary data.
🧠 Conceptual
expert2:00remaining
Effect of astype() on DataFrame copy behavior
Which statement about astype() behavior is TRUE?
Attempts:
2 left
💡 Hint
Check if astype() has an inplace parameter.
✗ Incorrect
astype() returns a new DataFrame or Series with converted types and does not modify the original unless reassigned.