0
0
Data Analysis Pythondata~15 mins

Changing data types (astype) in Data Analysis Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Changing Data Types with astype
📖 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.