📖 Scenario: You work in a small store and have a list of products with their prices and quantities. The data was entered as text, but you need to convert the prices and quantities to numbers to do calculations.
🎯 Goal: You will create a pandas DataFrame with product data, then convert the price and quantity columns from text to the correct number types using astype(). Finally, you will print the updated DataFrame.
📋 What You'll Learn
Create a pandas DataFrame with product names, prices, and quantities as strings
Create a variable to hold the list of columns to convert
Use astype() to convert the price column to float and quantity column to integer
Print the final DataFrame to see the changes
💡 Why This Matters
🌍 Real World
Stores and businesses often get data as text but need to convert it to numbers for calculations like totals and averages.
💼 Career
Data analysts and scientists frequently convert data types to prepare data for analysis and visualization.
Progress0 / 4 steps
1
Create the initial DataFrame with product data
Import pandas as pd. Create a DataFrame called products with these exact columns and values: 'Product': ['Apple', 'Banana', 'Carrot'], 'Price': ['0.50', '0.30', '0.20'], 'Quantity': ['10', '20', '30']. All values should be strings.
Pandas
Hint
Use pd.DataFrame() with a dictionary where keys are column names and values are lists of strings.
2
Create a list of columns to convert
Create a list called cols_to_convert that contains the exact column names 'Price' and 'Quantity'.
Pandas
Hint
Just assign the list ['Price', 'Quantity'] to the variable cols_to_convert.
3
Convert the columns to correct types using astype()
Use astype() to convert the 'Price' column to float and the 'Quantity' column to int. Update the products DataFrame with these conversions.
Pandas
Hint
Use products['Price'] = products['Price'].astype(float) and similarly for 'Quantity' with int.
4
Print the updated DataFrame
Print the products DataFrame to see the updated data types and values.
Pandas
Hint
Use print(products) to show the DataFrame.
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
Step 1: Understand the purpose of astype()
The astype() method is used to convert the data type of a pandas Series or DataFrame column.
Step 2: Compare with other options
Sorting, filtering, and merging are different pandas operations unrelated to astype().
Final Answer:
It changes the data type of a DataFrame column or Series. -> Option B
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
Step 1: Recall the method syntax
The correct syntax to convert a Series is Series.astype(type), so col.astype(int) is correct.
Step 2: Check other options
Options B, C, and D are not valid pandas syntax for type conversion.
Final Answer:
col.astype(int) -> Option C
Quick Check:
Use Series.astype(type) = A [OK]
Hint: Use series.astype(type) to convert types [OK]
D. TypeError because astype() cannot convert strings
Solution
Step 1: Identify data in column 'B'
Column 'B' contains strings '10', '20', and 'thirty'. 'thirty' is not numeric.
Step 2: Understand astype(int) behavior
Trying to convert 'thirty' to int causes a ValueError because it cannot be parsed as a number.
Final Answer:
ValueError due to non-numeric string 'thirty' -> Option A
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
Step 1: Understand the problem with astype()
Using astype(float) fails if there are non-numeric strings, causing errors.
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).
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.
Final Answer:
df['score'] = pd.to_numeric(df['score'], errors='coerce').fillna(0.0) -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.