NumPy Data Types
NumPy arrays store elements using precise data types called dtypes, which determine how much memory each element uses and how it behaves in operations.
Data Types in NumPy
Python already provides int, float, str, and bool, but NumPy needs finer control over memory and performance, so it defines a richer set of data types identified by short one-letter codes such as i for integer and f for float. Every ndarray has a dtype attribute you can read at any time to see exactly which type its elements share.
Example
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
arr2 = np.array(['apple', 'banana', 'cherry'])
print(arr2.dtype)
# Output:
# int64
# <U6The Type Character Codes
- i - integer
- u - unsigned integer
- f - float
- b - boolean
- c - complex float
- m - timedelta
- M - datetime
- O - object
- S - byte string
- U - unicode string
- V - void, a fixed chunk of memory
Creating Arrays With a Defined Data Type
Example
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
arr2 = np.array([1, 2, 3, 4], dtype='i4')
print(arr2)
print(arr2.dtype)
# Output:
# [b'1' b'2' b'3' b'4']
# |S1
# [1 2 3 4]
# int32Note: Pass dtype='S' for a byte string or 'i4' for a 4-byte integer and NumPy casts every element for you. But if a value truly cannot convert, such as 'a' in dtype='i', NumPy raises a ValueError immediately, so validate your data before forcing a numeric dtype.
Converting Data Type on Existing Arrays - astype()
Example
import numpy as np
arr = np.array([1.1, 2.1, 3.9])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
newarr2 = arr.astype(int)
print(newarr2)
boolarr = np.array([1, 0, 3])
newarr3 = boolarr.astype(bool)
print(newarr3)
# Output:
# [1 2 3]
# int32
# [1 2 3]
# [ True False True]Note: astype() always returns a new array and never modifies the original in place. It also truncates floating point values toward zero rather than rounding, so 3.9 becomes 3, not 4 - call np.round() first if you need conventional rounding.
Exercise: NumPy Data Types
How can you check the data type of a NumPy array's elements?