📖 Scenario: You work in a small store and keep track of sales data. Sometimes the numbers are saved as text, but you need them as numbers to do math.
🎯 Goal: You will change the data types of sales data from text to numbers using astype so you can analyze it easily.
📋 What You'll Learn
Create a pandas DataFrame with sales data as strings
Create a list of columns to convert
Use astype to change the data types of those columns to integers
Print the DataFrame to see the changes
💡 Why This Matters
🌍 Real World
Stores and businesses often get data as text but need numbers to calculate totals, averages, or do other analysis.
💼 Career
Data analysts and scientists frequently convert data types to prepare data for calculations and visualizations.
Progress0 / 4 steps
1
Create the sales data DataFrame
Create a pandas DataFrame called sales with these columns and string values: 'Product' with values 'Pen', 'Notebook', 'Eraser'; 'Quantity' with values '10', '5', '8'; and 'Price' with values '1.5', '3.0', '0.5'.
Data Analysis Python
Hint
Use pd.DataFrame with a dictionary where each key is a column name and each value is a list of strings.
2
Create a list of columns to convert
Create a list called cols_to_convert containing the column names 'Quantity' and 'Price' that you want to change from strings to numbers.
Data Analysis Python
Hint
Make a list with the exact column names as strings.
3
Convert the columns to numeric types
Use astype on the sales DataFrame to convert the columns in cols_to_convert to numeric types. Convert 'Quantity' to integers and 'Price' to floats. Assign the result back to sales[cols_to_convert].
Data Analysis Python
Hint
Use sales['Quantity'].astype(int) and sales['Price'].astype(float) to convert each column separately.
4
Print the updated DataFrame
Print the sales DataFrame to see the columns 'Quantity' and 'Price' as numbers.
Data Analysis Python
Hint
Use print(sales) 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.
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
Filtering, sorting, and merging are different pandas operations and not related to changing data types.
Final Answer:
It changes the data type of a DataFrame column. -> Option B
The 'score' column starts as strings (object type) because values are in quotes.
Step 2: Apply astype(int) conversion
Using astype(int) converts the column to integer type, which pandas shows as int64.
Step 3: Check the printed dtypes output
The output shows the column name and its type, followed by dtype info. The correct output is: score int64 dtype: int64
Final Answer:
score int64
dtype: int64 -> Option A
Quick Check:
astype(int) converts to int64 dtype [OK]
Hint: astype(int) changes string numbers to int64 type [OK]
Common Mistakes:
Expecting dtype to be 'object' after conversion
Confusing dtype display format
Thinking astype changes values, not type
4. What error will occur if you try to convert a pandas column with non-numeric strings to integer using astype(int)?
medium
A. KeyError: column not found
B. TypeError: unsupported operand type(s)
C. ValueError: invalid literal for int() with base 10
D. No error, conversion succeeds
Solution
Step 1: Understand what astype(int) expects
The method expects values that can be converted to integers, like numeric strings or numbers.
Step 2: Consider non-numeric strings
If the column contains strings like 'abc', conversion to int is impossible and raises a ValueError.
Step 3: Identify the error message
The error message is: ValueError: invalid literal for int() with base 10.
Final Answer:
ValueError: invalid literal for int() with base 10 -> Option C
Quick Check:
Non-numeric strings cause ValueError on astype(int) [OK]
Hint: Non-numeric strings cause ValueError on int conversion [OK]
Common Mistakes:
Expecting silent failure or automatic conversion
Confusing ValueError with TypeError
Thinking KeyError relates to conversion
5. You have a DataFrame with a column 'price' containing numbers as strings with dollar signs, like '$100', '$250'. How do you convert this column to float type for calculations?
hard
A. df['price'] = df['price'].str.replace('$', '').astype(float)
B. df['price'] = df['price'].astype(float)
C. df['price'] = df['price'].replace('$', '').astype(float)
D. df['price'] = df['price'].astype(str).astype(float)
Solution
Step 1: Remove dollar signs from strings
Dollar signs prevent direct conversion to float. Use str.replace('$', '') to remove them.
Step 2: Convert cleaned strings to float
After removing '$', use astype(float) to convert the column to float type.
Step 3: Check other options
df['price'] = df['price'].astype(float) tries to convert without removing '$' causing error. df['price'] = df['price'].replace('$', '').astype(float) uses replace without str accessor, which won't work on strings. df['price'] = df['price'].astype(str).astype(float) converts to string again unnecessarily.
Final Answer:
df['price'] = df['price'].str.replace('$', '').astype(float) -> Option A
Quick Check:
Remove symbols first, then astype(float) [OK]
Hint: Remove symbols with str.replace before astype(float) [OK]
Common Mistakes:
Trying to convert strings with symbols directly
Using replace without str accessor on strings
Double converting types unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.