0
0
Pandasdata~15 mins

astype() for type conversion in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using astype() for Type Conversion in pandas
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(products) to show the DataFrame.