NumPy Data Types Explained

Aarav Iyer
2 min readJan 12, 2024

--

Python has various in-built data types like int, float, str, complex, etc.

You can read more about Data Types of Python here-

License: https://creativecommons.org/licenses/by-sa/4.0/

The data types of NumPy are slightly different. NumPy has some extra data types, and all the data types are represented differently to that of Python’s.

The data types of NumPy are-

i-integer
u-unsigned integer (can store only positive values and 0)
f-floating point (decimal)
c-complex float
b-boolean
S-string
U-unicode string
O-object
M-datetime (for date and time)
m-timedelta (extension for M)
O-object
V-void

Checking the Data Type of an Array

The data type of a NumPy array can be checked using the dtype property.

For example-

import numpy as np

arr=np.array([1,2,3,4,5])

print(arr.dtype)

The output-

int64

Here, the int64 signifies that the array is a 64-bit integer.

Similarly, you can check it for other values in arrays too.

Defining Data Types of Arrays

You can define the data type of a NumPy array using the array() function and the dtype argument.

For example-

import numpy as np

arr=np.array([1,2,3,4,5], dtype='i')

print(arr)

The output-

[1 2 3 4 5]

In case of i, u, f, S andU, you can give the size in bits too.

For example-

import numpy as np

arr=np.array([1,2,3,4], dtype='i4')

print(arr)

The output-

[1 2 3 4]
int32

Changing Data Types of Arrays

The data type of an existing array cannot be changed.

However, you can create a duplicate array with the required data type using the astype() function.

You can change the data type using both Python data types and NumPy data types.

For example, using NumPy data types-

import numpy as np

arr=np.array([1.4, 5.2, 9.1])

new_arr=arr.astype('i')

print(new_arr)
print(new_arr.dtype)

The output-

[1 5 9]
int32

Now, using Python data types-

import numpy as np

arr=np.array([1.4, 5.2, 9.1])

new_arr=arr.astype(int)

print(new_arr)
print(new_arr.dtype)

The output-

[1 5 9]
int64

Changing the data type to Boolean

While changing the data type to boolean, all numbers except 0 are considered True, while 0 is considered False.

Read more about Boolean data types-

For example-

import numpy as np

arr=np.array([1, -5, 9, 0])

new_arr=arr.astype(bool)

print(new_arr)
print(new_arr.dtype)

The output-

[ True  True  True False]
bool

That is all for now. Applaud this story if you liked it and follow me for more such content on coding and Python.

Happy coding,

Aarav Iyer

--

--

Aarav Iyer
Aarav Iyer

Written by Aarav Iyer

A tech enthusiast learning Python and interested in anything related to space and the Universe.

No responses yet