0
0
Pandasdata~20 mins

astype() for type conversion in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
astype() Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A
   score
0     95
1     88
2     76
B
   score
0     96
1     88
2     77
C
   score
0    95.7
1    88.2
2    76.9
D
   score
0    95.0
1    88.0
2    76.0
Attempts:
2 left
💡 Hint
astype(int) truncates the decimal part without rounding.
data_output
intermediate
2: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)
A
A    float64
B      int32
dtype: object
B
A      int64
B    float64
dtype: object
C
A      int32
B      int32
dtype: object
D
A    float64
B    float64
dtype: object
Attempts:
2 left
💡 Hint
Check the specified types in the astype dictionary.
🔧 Debug
advanced
2: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)
AKeyError: 'age'
BTypeError: cannot convert string to int
CValueError: invalid literal for int() with base 10: 'thirty'
DNo error, conversion succeeds
Attempts:
2 left
💡 Hint
Check if all strings can be converted to int.
🚀 Application
advanced
2: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]})
Adf['flag'] = df['flag'].astype('object')
Bdf['flag'] = df['flag'].astype('int64')
Cdf['flag'] = df['flag'].astype('float32')
Ddf['flag'] = df['flag'].astype('bool')
Attempts:
2 left
💡 Hint
Boolean type uses less memory than integer types.
🧠 Conceptual
expert
2:00remaining
Effect of astype() on DataFrame copy behavior
Which statement about astype() behavior is TRUE?
Aastype() returns a new DataFrame only if the dtype changes; otherwise, it returns the original.
Bastype() always returns a new DataFrame and never modifies the original in place.
Castype() modifies the original DataFrame in place and returns the same object.
Dastype() modifies the original DataFrame in place without returning anything.
Attempts:
2 left
💡 Hint
Check if astype() has an inplace parameter.