0
0
NumPydata~5 mins

Type casting with astype() in NumPy

Choose your learning style9 modes available
Introduction

Type casting changes the data type of array elements. It helps when you need numbers as integers or floats for calculations.

You have decimal numbers but want to work with whole numbers only.
You want to save memory by converting large float arrays to smaller integer types.
You need to convert numbers to strings for display or export.
You want to prepare data for a function that requires a specific type.
You want to convert boolean values to integers for counting.
Syntax
NumPy
array.astype(new_type)

array is your NumPy array.

new_type can be a type like int, float, str, or NumPy types like np.int32.

Examples
Converts float numbers to integers by dropping decimals.
NumPy
import numpy as np
arr = np.array([1.5, 2.3, 3.7])
arr_int = arr.astype(int)
print(arr_int)
Converts integers to boolean values (0 becomes False, others True).
NumPy
import numpy as np
arr = np.array([1, 0, 1])
arr_bool = arr.astype(bool)
print(arr_bool)
Converts numbers to strings.
NumPy
import numpy as np
arr = np.array([1, 2, 3])
arr_str = arr.astype(str)
print(arr_str)
Sample Program

This program shows how to change the type of a NumPy array from float to int, string, and boolean using astype().

NumPy
import numpy as np

# Original array with floats
arr = np.array([4.7, 5.2, 6.9])
print('Original array:', arr)

# Convert to integers
arr_int = arr.astype(int)
print('As integers:', arr_int)

# Convert to strings
arr_str = arr.astype(str)
print('As strings:', arr_str)

# Convert to boolean
arr_bool = arr_int.astype(bool)
print('As booleans:', arr_bool)
OutputSuccess
Important Notes

When converting floats to integers, decimals are dropped (not rounded).

Converting to boolean treats zero as False and any other number as True.

Use astype() to create a new array; the original array stays the same.

Summary

astype() changes the data type of a NumPy array.

It is useful to prepare data for different tasks or save memory.

Always remember it returns a new array and does not change the original.