Change the Data Type of the Given NumPy Array
Last Updated :
02 Feb, 2024
NumPy arrays are homogenous, meaning all elements in a NumPy array are of the same data type and referred to as array type. You might want to change the data type of the NumPy array to perform some specific operations on the entire data set.
In this tutorial, we are going to see how to change the data type of the given NumPy array. We will use the astype() function of the NumPy library to change the data type of the NumPy array.
NumPy astype() Method
The numpy.astype() method is used to change the data type NumPy array from one data type to another.
The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.
Syntax
Syntax: ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
Parameters:
- dtype: The data type you want to change into.
- order: Controls the memory layout order of the result. Options are ‘C’, ‘F’, ‘A’, ‘K’.
- casting: Controls the type of data casting. Options are ‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’.
- subok: If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array.
- copy: By default, astype() returns a newly allocated array. If set to false, the input array is returned instead of a copy.
Return: The method returns a new array with new data type.
Sample Programs
Here we will go through some Python programs to see how we can change data type of the given NumPy array. The problems will help you understand astype() function and the changes in specific data types.
Problem 1
Given a NumPy array whose underlying data is of 'int32' type. Change the data type of the given object to 'float64'.
Solution :
Using the NumPy.astype() function to change the data type of the underlying data of the given NumPy array.
Python3
import numpy as np
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
# Print the array
print(arr)
Output :

Now we will check the data type of the given array object with dtype property.
Python3
# Print the dtype
print(arr.dtype)
Output :

As we can see in the output, the current data type of the given array object is 'int32'. Now we will change this to 'float64' type.
Python3
# change the dtype to 'float64'
arr = arr.astype('float64')
print(arr)
# print the data type
print(arr.dtype)
Output :


Problem 2 :
Given a NumPy array whose underlying data is of 'int32' type. Change the data type of the given object to 'complex128'.
Solution :
We will use NumPy.astype() function to change the data type of the underlying data of the given NumPy array.
Python3
import numpy as np
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
print(arr)
Output :

Now we will check the data type of the given array object.
Python3
# Print the dtype
print(arr.dtype)
Output :

As we can see in the output, the current data type of the given array object is 'int32'. Now we will change this to 'complex128' type.
Python3
# change the dtype to 'complex128'
arr = arr = arr.astype('complex128')
print(arr)
# Also print the data type
print(arr.dtype)
Output :


Conclusion
Converting the data type (type) of a array in NumPy might be useful to perform datatype-specific operations on the entire data set. You can convert the data type of an entire array with the built-in NumPy library function astype().
In this tutorial, we have covered the best way to change the data type of the given NumPy array with astype() method. We have provided an easy explanation for the method and also covered sample problems/examples to provide a better understanding of the concept.
Similar Reads
Check data type in NumPy Numpy, is originally called numerical python, but in short, we pronounce it as Numpy. NumPy is a general-purpose array-processing package in Python. It provides high-performance multidimensional data structures like array objects and tools for working with these arrays. Numpy provides faster and mor
5 min read
How to Change a Single Value in a NumPy Array NumPy arrays are a fundamental data structure in Python, widely used for scientific computing and data analysis. They offer a powerful way to perform operations on large datasets efficiently. One common task when working with NumPy arrays is changing a single value within the array. This article wil
6 min read
How to Create Array of zeros using Numpy in Python numpy.zeros() function is the primary method for creating an array of zeros in NumPy. It requires the shape of the array as an argument, which can be a single integer for a one-dimensional array or a tuple for multi-dimensional arrays. This method is significant because it provides a fast and memory
4 min read
Different Ways to Create Numpy Arrays in Python Creating NumPy arrays is a fundamental aspect of working with numerical data in Python. NumPy provides various methods to create arrays efficiently, catering to different needs and scenarios. In this article, we will see how we can create NumPy arrays using different ways and methods. Ways to Create
3 min read
Data type Object (dtype) in NumPy Python Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about: Type of the data (integer, float, Python object, etc.)Size of the data (number of bytes)The byte order of the data (little-endia
3 min read
How to Fix "Can't Adapt Type 'numpy.int64'"? The error is âCanât adapt type ânumpy. int64ââ and occurs when the NumPy data types specific to a language are incompatible with other database or library types expected. This can be solved where, NumPy types are converted to native Python types or where one use the procedure of adaptation. All of t
5 min read
NumPy - Create array filled with all ones To create an array filled with all ones, given the shape and type of array, we can use numpy.ones() method of NumPy library in Python.Pythonimport numpy as np array = np.ones(5) print(array) Output:[1. 1. 1. 1. 1.] 2D Array of OnesWe can also create a 2D array (matrix) filled with ones by passing a
2 min read
Convert Numpy Array to Dataframe Converting a NumPy array into a Pandas DataFrame makes our data easier to understand and work with by adding names to rows and columns and giving us tools to clean and organize it.In this article, we will take a look at methods to convert a numpy array to a pandas dataframe. We will be discussing tw
4 min read
How To Convert Numpy Array To Tensor? We are given a NumPy array, and our task is to convert it into a TensorFlow tensor. This is useful when integrating NumPy-based data with TensorFlow pipelines, which support acceleration using GPU and TPU. For example, converting [[1, 2], [3, 4]] results in a TensorFlow object that looks like: Pytho
2 min read
Using NumPy to Convert Array Elements to Float Type There are often when we must convert an array in Python to a differing type. One of these times would be when given an array and having to convert it to an array of float types. This is often useful when conducting data analysis and there are a variety of ways of doing this. Whilst iterating through
5 min read