Every NumPy array has exactly one data type, called its dtype. The dtype decides how much memory each value uses and which operations are allowed.
Check the data type
Example
import numpy as np
ints = np.array([1, 2, 3])
floats = np.array([1.5, 2.0, 3.25])
words = np.array(["apple", "kiwi"])
print(ints.dtype)
print(floats.dtype)
print(words.dtype)
Output
int64
float64
<U5
<U5 means a Unicode string of up to 5 characters. The number in names like int64 is the size of each value in bits.
Common data types
dtype | Holds | Example |
|---|---|---|
| Whole numbers |
|
| Decimal numbers |
|
| True / False |
|
| Text (Unicode strings) |
|
| Complex numbers |
|
Choose a data type
Pass the dtype argument to create an array of a specific type:
Example
import numpy as np
arr = np.array([1, 2, 3], dtype="float64")
print(arr)
print(arr.dtype)
Output
[1. 2. 3.]
float64
Convert with astype()
astype() returns a new array with a different type. Converting floats to integers drops the decimal part — it does not round.
Example
import numpy as np
prices = np.array([9.99, 15.5, 3.2])
print(prices.astype(int))
flags = np.array([0, 1, 2, 0])
print(flags.astype(bool))
Output
[ 9 15 3]
[False True True False]
Mixed values are upcast
If you mix types, NumPy picks one type that can hold all of them. Integers and floats together become floats:
Example
import numpy as np
mixed = np.array([1, 2, 3.5])
print(mixed)
print(mixed.dtype)
Output
[1. 2. 3.5]
float64
If a value cannot be converted, NumPy raises a
ValueError— for examplenp.array(['a', '2'], dtype=int).