Changing dtype of a NumPy array

Last updated on November 24, 2021 A Goodman Loading... Post a comment

The examples below show you how to cast a NumPy array from a dtype to another dtype by using the astype method. One important thing to keep in mind here is that the astype doesn’t mutate the original array but always creates a new array (a copy of the data), even if the new dtype is the same as the old dtype.

Example 1

From np.int32 to np.float64:

import numpy as np

a = np.array([1, 2, 3, 4, 0], dtype=np.int32)
b = a.astype(np.float64)

b.dtype

Output:

dtype('float64')

Example 2

If you cast an array of floating-point numbers into an array of integers, the decimal part will be truncated.

import numpy as np

x = np.array([1.12, 2.03, 3.05, 5.10])
y = x.astype(dtype=np.int32)

y

Output:

array([1, 2, 3, 5], dtype=int32)

Example 3

Convert an array of numeric strings to an array of floating-point:

import numpy as np

arr_strings = np.array(['1.1', '2.2', '3.3', '40'])
arr_numbers = arr_strings.astype(np.float64)

arr_numbers

Output:

array([ 1.1,  2.2,  3.3, 40. ])

Further reading:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like