Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Creating Arrays With a Defined Data Type

We utilize the array() function to create arrays, which can include an optional argument, dtype, that allows us to specify the desired data type for the array elements.

Example

Create an array with the data type set to string.

import numpy as np

arr = np.array([1234], dtype=‘S’)

print(arr)
print(arr.dtype)

For data types i, u, f, S, and U, we can also specify the size.

Example

Create an array with a data type of 4-byte integer.

import numpy as np

arr = np.array([1234], dtype=‘i4’)

print(arr)
print(arr.dtype)

What if a Value Can Not Be Converted?

If a type is specified that cannot accommodate the elements, NumPy will raise a ValueError.

In Python, a ValueError is raised when an argument passed to a function is of an unexpected or incorrect type.

Example

A non-integer string, such as ‘a’, cannot be converted to an integer and will raise an error.

import numpy as np

arr = np.array([‘a’‘2’‘3’], dtype=‘i’)