Bird
Raised Fist0
Pandasdata~20 mins

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

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

Practice

(1/5)
1. What does the astype() method do in pandas?
easy
A. It filters rows based on a condition.
B. It changes the data type of a DataFrame column or Series.
C. It sorts the DataFrame by column values.
D. It merges two DataFrames together.

Solution

  1. Step 1: Understand the purpose of astype()

    The astype() method is used to convert the data type of a pandas Series or DataFrame column.
  2. Step 2: Compare with other options

    Sorting, filtering, and merging are different pandas operations unrelated to astype().
  3. Final Answer:

    It changes the data type of a DataFrame column or Series. -> Option B
  4. Quick Check:

    astype() changes types = C [OK]
Hint: Remember: astype() changes data types only [OK]
Common Mistakes:
  • Confusing astype() with sorting or filtering methods
  • Thinking astype() modifies data values instead of types
  • Assuming astype() merges DataFrames
2. Which of the following is the correct syntax to convert a pandas Series col to integer type?
easy
A. col.convert(int)
B. astype(col, int)
C. col.astype(int)
D. col.to_int()

Solution

  1. Step 1: Recall the method syntax

    The correct syntax to convert a Series is Series.astype(type), so col.astype(int) is correct.
  2. Step 2: Check other options

    Options B, C, and D are not valid pandas syntax for type conversion.
  3. Final Answer:

    col.astype(int) -> Option C
  4. Quick Check:

    Use Series.astype(type) = A [OK]
Hint: Use series.astype(type) to convert types [OK]
Common Mistakes:
  • Using astype as a standalone function
  • Trying non-existent methods like to_int()
  • Passing arguments in wrong order
3. What will be the output of this code?
import pandas as pd
df = pd.DataFrame({'A': ['1', '2', '3']})
df['A'] = df['A'].astype(int)
print(df.dtypes['A'])
medium
A. int64
B. string
C. float64
D. object

Solution

  1. Step 1: Understand the initial data type

    Column 'A' starts as strings (object type) because values are in quotes.
  2. Step 2: Apply astype(int)

    Converting with astype(int) changes the type to integer, which pandas shows as int64.
  3. Final Answer:

    int64 -> Option A
  4. Quick Check:

    astype(int) converts to int64 = D [OK]
Hint: astype(int) converts string numbers to int64 type [OK]
Common Mistakes:
  • Expecting type to remain object after conversion
  • Confusing int64 with float64
  • Thinking astype changes values but not type
4. What is wrong with this code snippet?
import pandas as pd
df = pd.DataFrame({'B': ['10', '20', 'thirty']})
df['B'] = df['B'].astype(int)
medium
A. ValueError due to non-numeric string 'thirty'
B. No error, code runs fine
C. SyntaxError because of missing parentheses
D. TypeError because astype() cannot convert strings

Solution

  1. Step 1: Identify data in column 'B'

    Column 'B' contains strings '10', '20', and 'thirty'. 'thirty' is not numeric.
  2. Step 2: Understand astype(int) behavior

    Trying to convert 'thirty' to int causes a ValueError because it cannot be parsed as a number.
  3. Final Answer:

    ValueError due to non-numeric string 'thirty' -> Option A
  4. Quick Check:

    Non-numeric string causes ValueError = B [OK]
Hint: Non-numeric strings cause ValueError on astype(int) [OK]
Common Mistakes:
  • Assuming astype silently converts all strings
  • Confusing ValueError with SyntaxError
  • Thinking astype() can convert any string
5. You have a DataFrame df with a column 'score' containing float values as strings like '85.5'. You want to convert this column to numeric floats but also handle any non-numeric values by replacing them with 0.0. Which code correctly does this?
hard
A. df['score'] = df['score'].convert(float, fill=0.0)
B. df['score'] = df['score'].astype(float).fillna(0.0)
C. df['score'] = df['score'].astype(int).fillna(0)
D. df['score'] = pd.to_numeric(df['score'], errors='coerce').fillna(0.0)

Solution

  1. Step 1: Understand the problem with astype()

    Using astype(float) fails if there are non-numeric strings, causing errors.
  2. Step 2: Use pd.to_numeric() with error handling

    pd.to_numeric() with errors='coerce' converts invalid values to NaN, which can be replaced by fillna(0.0).
  3. Step 3: Check other options

    df['score'] = df['score'].astype(float).fillna(0.0) does not handle errors properly; df['score'] = df['score'].astype(int).fillna(0) converts to int, losing decimals; df['score'] = df['score'].convert(float, fill=0.0) uses a non-existent method.
  4. Final Answer:

    df['score'] = pd.to_numeric(df['score'], errors='coerce').fillna(0.0) -> Option D
  5. Quick Check:

    Use pd.to_numeric with errors='coerce' + fillna = A [OK]
Hint: Use pd.to_numeric with errors='coerce' to handle bad data [OK]
Common Mistakes:
  • Using astype(float) without error handling
  • Trying to convert to int losing decimals
  • Using non-existent methods like convert()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard