0
0
Data Analysis Pythondata~20 mins

Changing data types (astype) in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Data Type Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code after changing data types?
Given the DataFrame below, what will be the data type of column 'A' after applying astype('float')?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'A': ['1', '2', '3'], 'B': [4, 5, 6]})
df['A'] = df['A'].astype('float')
print(df['A'].dtype)
Astring
Bint64
Cobject
Dfloat64
Attempts:
2 left
💡 Hint
Think about what astype('float') does to string numbers.
data_output
intermediate
2:00remaining
What is the resulting DataFrame after type conversion?
What will be the output DataFrame after converting column 'C' to integers?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'C': [1.1, 2.5, 3.9]})
df['C'] = df['C'].astype('int')
print(df)
A
   C
0  2
1  3
2  4
B
   C
0  1
1  2
2  3
C
   C
0  1.1
1  2.5
2  3.9
D
   C
0  1
1  3
2  4
Attempts:
2 left
💡 Hint
Remember that converting float to int truncates the decimal part.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error?
This code tries to convert a column with mixed types to integer. What error does it raise?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'D': ['10', 'twenty', '30']})
df['D'] = df['D'].astype('int')
AValueError: invalid literal for int() with base 10: 'twenty'
BTypeError: cannot convert float to int
CKeyError: 'D'
DSyntaxError: invalid syntax
Attempts:
2 left
💡 Hint
Look at the string 'twenty' and think about converting it to int.
🧠 Conceptual
advanced
2:00remaining
Which data type conversion is NOT possible with astype()?
Which of the following conversions using astype() will raise an error?
AConverting a string column with non-numeric text to float
BConverting an integer column to boolean
CConverting a float column to string
DConverting a boolean column to integer
Attempts:
2 left
💡 Hint
Think about converting text that is not a number to a numeric type.
🚀 Application
expert
3:00remaining
How many unique data types are in this DataFrame after conversions?
After running the code below, how many unique data types are present in the DataFrame?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({
    'X': ['1', '2', '3'],
    'Y': [1.0, 2.0, 3.0],
    'Z': [True, False, True]
})
df['X'] = df['X'].astype('int')
df['Y'] = df['Y'].astype('int')
df['Z'] = df['Z'].astype('int')
print(df.dtypes.nunique())
A4
B3
C1
D2
Attempts:
2 left
💡 Hint
Check the data types after conversion carefully.