Data Type Conversion and Casting
Learn how to convert NumPy arrays between integer, floating-point, Boolean, and string data types. Understand astype(), explicit dtype selection, type promotion, precision, and safe data handling.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand data type conversion in NumPy.
- Convert arrays using the astype() method.
- Convert integers to floating-point values.
- Convert floating-point values to integers.
- Convert numeric arrays to Boolean and string types.
- Specify data types during array creation.
- Understand type promotion in arithmetic operations.
- Identify precision loss and possible conversion errors.
- Inspect an array's dtype before and after conversion.
- Apply data type conversion to practical datasets.
astype() when
you want to create a converted array. Always inspect the resulting
dtype and check whether conversion changes the original values.
2. What Is Data Type Conversion?
Data type conversion is the process of changing how values are represented in an array. For example, an integer array can be converted into a floating-point array to support decimal values.
NumPy provides the astype() method for converting
array elements to a requested data type. Conversion is useful
when preparing datasets, performing calculations, and managing
memory.
Example: Converting Integers to Floats
Output
The converted array stores the values using a floating-point data type. The original array remains unchanged.
3. Using astype() to Convert Data Types
The astype() method accepts a target data type and
returns a new array containing converted values.
Common Conversion Targets
| Target Type | Example | Typical Purpose |
|---|---|---|
np.int32 |
values.astype(np.int32) |
Store whole-number values using a 32-bit integer type. |
np.float32 |
values.astype(np.float32) |
Represent values using 32-bit floating-point numbers. |
np.float64 |
values.astype(np.float64) |
Use 64-bit floating-point representation. |
np.bool_ |
values.astype(np.bool_) |
Convert values to Boolean representations. |
str |
values.astype(str) |
Convert values to strings. |
astype() returns a new
array by default. Assign the result to a variable if you want
to use the converted values later.
4. Converting Floating-Point Values to Integers
Floating-point arrays can be converted to integer arrays. For finite floating-point values, the fractional part is discarded during conversion to an integer type.
Output
The conversion does not round the values to the nearest integer. For example, 12.8 becomes 12 rather than 13.
Conversion vs. Rounding
Use astype() when you need a type conversion.
Use np.round() when you want to round numerical
values.
5. Converting Integers to Floating-Point Values
Integer values can be converted to floating-point values when decimal calculations are required. The conversion represents the integer values using a floating-point data type.
Output
Floating-point conversion is useful when a calculation involves decimal values, although NumPy's arithmetic operations may already promote types when required.
6. Converting Numeric Values to Boolean
NumPy's Boolean type is represented by np.bool_.
When ordinary numeric values are converted to Boolean values,
zero becomes False and nonzero values become True.
Boolean Conversion Rules
| Numeric Value | Boolean Result |
|---|---|
0 |
False |
1 |
True |
25 |
True |
-3 |
True |
values > 0.
7. Converting Values to Strings
Numeric arrays can be converted to string arrays using
astype(str). This is useful when preparing
values for text-based output or certain reporting tasks.
The resulting elements are strings rather than numeric values. Arithmetic operations that require numbers may therefore behave differently or fail until the values are converted back.
Converting Numeric Text Back to Numbers
"hello" cannot be converted directly to an
integer or floating-point value using ordinary astype() conversion.
8. Specifying a Data Type During Array Creation
Instead of converting an existing array later, you can specify
a target data type while creating an array using the
dtype parameter.
When to Use dtype and astype()
| Method | Example | Use Case |
|---|---|---|
dtype parameter |
np.array([1, 2], dtype=np.float32) |
Choose the type when creating an array. |
astype() |
array.astype(np.float32) |
Convert an existing array to another type. |
dtype during
construction when you already know the desired type.
Use astype() when you need to convert an existing array.
9. Understanding Type Promotion
NumPy may promote values to a common data type when arrays of different types are combined in an operation. This helps represent the result appropriately.
Output
In this example, the result uses a floating-point data type to represent the decimal values. The precise result type depends on the input types and the operation being performed.
NumPy's true-division operation generally produces floating-point results even when the inputs are integers.
dtype after arithmetic operations if the data type
is important to your application.
10. Precision, Range, and Safe Conversion
Different data types support different numerical ranges and precision levels. Selecting an unsuitable type can lead to information loss or unexpected results.
Common Conversion Risks
| Conversion | Possible Risk | Recommended Check |
|---|---|---|
| Float to integer | Fractional parts are discarded. | Check whether decimal precision is required. |
| Large integer to smaller integer | Values may not fit in the target range. | Check the target type's supported range. |
| Float64 to float32 | Precision may be reduced. | Compare the precision requirements. |
| String to numeric | Invalid text may cause conversion errors. | Validate the input strings first. |
| Numeric to Boolean | Nonzero values all become True. | Use a comparison when a specific condition is needed. |
11. Common Data Type Conversion Errors
| Problem | Reason | Solution |
|---|---|---|
| Invalid string conversion | The source text cannot be parsed as the target type. | Validate and clean text before conversion. |
| Unexpected loss of decimals | Floating-point values were converted to integers. | Use a floating-point target type if decimals are required. |
| Unexpected Boolean results | Every nonzero number converts to True. | Use a comparison for the intended condition. |
| Insufficient integer range | The target integer type cannot represent all values. | Choose an appropriate integer type. |
| Unexpected output dtype | NumPy promoted the input types during an operation. | Inspect the resulting dtype. |
12. Practical Activity: Student Marks Conversion
Activity: Convert and Analyze Marks
Samiksha is preparing student marks for numerical analysis. Convert integer marks to floating-point values, calculate the average, and compare the original and converted arrays.
Expected Output
This activity demonstrates how to convert data types, inspect the resulting dtype, calculate an average, and recognize the loss of fractional parts during integer conversion.
13. Practice Exercises
Use the following arrays to complete the exercises:
- Convert the values array to float64.
- Convert the prices array to int32 and observe the fractional parts.
- Convert the values array to strings.
- Convert the numeric text values to integers.
- Convert the numeric array
[0, 1, 2, 0]to Boolean values. - Create an array using
dtype=np.float32. - Print the dtype before and after each conversion.
- Explain the difference between astype() and the dtype parameter.
Challenge Exercise
Pradnya is preparing a sales dataset containing integer quantities and decimal prices. Write a program that:
- Creates an integer array for product quantities.
- Creates a floating-point array for product prices.
- Converts the quantities to float32.
- Calculates the total price for each product.
- Inspects the resulting dtype.
- Explains why converting prices to integers may lose information.
Summary
In this lesson, we learned how to convert NumPy arrays using
astype() and how to specify data types when
creating arrays.
We converted integer values to floating-point values, converted floating-point values to integers, and explored Boolean and string conversions. We also learned about type promotion, numerical precision, supported ranges, and common conversion errors. These concepts help maintain data quality during numerical processing. Practice converting arrays and checking the resulting dtype before using the converted values in calculations.