NumPy Data Types

๐Ÿ”  NumPy โ€” Data Types (dtype)

NumPy uses its own optimized data types rather than Pythonโ€™s built-in types.
These data types allow faster computation and less memory usage, especially when working with large datasets.


๐Ÿ“Œ Checking the Data Type

import numpy as np

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

Output:

int32 (or int64 depending on system)

๐Ÿง  Common NumPy Data Types

NumPy Type Meaning
i / int_ Integer
b Boolean
u Unsigned Integer (no negative values)
f Float
c Complex float
S String
U Unicode string
O Python object
M DateTime
m Time delta

๐Ÿงฎ Integer Types

arr = np.array([10, 20, 30], dtype='int8')
print(arr.dtype)

Possible integer sizes:

Type Range
int8 โˆ’128 โ†’ +127
int16 โˆ’32,768 โ†’ +32,767
int32 Standard integer
int64 Large integer

๐Ÿ”ข Float Types

arr = np.array([1.2, 3.14, 5.67], dtype='float32')
print(arr.dtype)

Float types:

Type Precision
float16 half precision
float32 single precision
float64 double precision

โž• Complex Numbers

arr = np.array([1+2j, 3+4j], dtype='complex128')
print(arr.dtype)

๐Ÿ”ฃ String and Unicode

arr = np.array(['hello', 'numpy'], dtype='S')
print(arr.dtype)

For Unicode:

arr = np.array(['numpy', 'python'], dtype='U')

โœ” Boolean Type

arr = np.array([True, False, True])
print(arr.dtype)

๐ŸŽฏ Converting (Casting) Data Type (astype())

You can convert (cast) an array to another type using astype().

arr = np.array([1.5, 2.8, 3.3])
new_arr = arr.astype('int')
print(new_arr)
print(new_arr.dtype)

โš  Casting Rules

โœ” Allowed: float โ†’ int, int โ†’ float
โŒ Not allowed automatically: string โ†’ numeric (unless values are valid numbers)

Example:

arr = np.array(["1", "2", "3"])
new = arr.astype(int)
print(new)

๐Ÿง  Memory Efficiency Example

import numpy as np

a = np.array([1,2,3,4,5], dtype=np.int8)
b = np.array([1,2,3,4,5], dtype=np.int64)

print(a.itemsize) # size of each element in bytes
print(b.itemsize)


๐Ÿ“Œ Summary Table

Category Example
Integer types int8, int16, int32, int64
Float types float16, float32, float64
Complex numbers complex64, complex128
Boolean bool_
Strings S (byte string), U (Unicode)
Date/time datetime64, timedelta64

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *