0
0
NumPydata~15 mins

Type casting with astype() in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Type Casting with astype() in NumPy
📖 Scenario: You are working with a small dataset of product prices stored as floating-point numbers. You want to convert these prices to integers to simplify further calculations.
🎯 Goal: Learn how to use the astype() method in NumPy to change the data type of an array.
📋 What You'll Learn
Create a NumPy array with specific float values
Create a variable to hold the target data type
Use astype() to convert the array to integers
Print the converted array
💡 Why This Matters
🌍 Real World
In data science, data often comes in different formats. Converting data types helps prepare data for analysis or machine learning.
💼 Career
Knowing how to change data types with NumPy is essential for data cleaning and preprocessing tasks in data science roles.
Progress0 / 4 steps
1
Create a NumPy array with float values
Import NumPy as np and create a NumPy array called prices with these float values: 19.99, 5.49, 3.50, 12.75, 7.30.
NumPy
Need a hint?

Use np.array([...]) to create the array with the exact float values.

2
Create a variable for the target data type
Create a variable called target_type and set it to int to specify the desired data type for conversion.
NumPy
Need a hint?

Just assign int to the variable target_type.

3
Convert the array to integers using astype()
Create a new variable called prices_int by converting the prices array to integers using the astype() method with the target_type variable.
NumPy
Need a hint?

Use prices.astype(target_type) to convert the array.

4
Print the converted integer array
Print the prices_int array to see the integer values after conversion.
NumPy
Need a hint?

Use print(prices_int) to display the converted array.