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.
Create an array with the data type set to string.
import numpy as np arr = np.array([1, 2, 3, 4], dtype=‘S’) print(arr) print(arr.dtype) |
For data types i, u, f, S, and U, we can also specify the size.
Create an array with a data type of 4-byte integer.
import numpy as np arr = np.array([1, 2, 3, 4], dtype=‘i4’) print(arr) print(arr.dtype) |
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. |
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’) |