NumPy Data Types
NumPy provides a wide range of data types to efficiently handle numerical and array-based computations. These types ensure better performance and memory optimization compared to Python’s native data types.
Commonly Used NumPy Data Types
| Data Type | Description | Example |
|---|---|---|
int32 | 32-bit integer | np.array([1, 2, 3]) |
float64 | 64-bit floating-point number | np.array([1.1, 2.2]) |
complex128 | Complex number (real + imaginary) | np.array([1 + 2j]) |
bool_ | Boolean values (True, False) | np.array([True]) |
str_ | Fixed-length Unicode strings | np.array(["Hello"]) |
object_ | Arbitrary Python objects | np.array([object]) |
Example: Specifying Data Types
import numpy as np
# Create arrays with specific data types
int_array = np.array([1, 2, 3], dtype='int32')
float_array = np.array([1.1, 2.2, 3.3], dtype='float64')
print("Integer Array:", int_array)
print("Data Type:", int_array.dtype)
print("Float Array:", float_array)
print("Data Type:", float_array.dtype)Output:
Integer Array: [1 2 3]
Data Type: int32
Float Array: [1.1 2.2 3.3]
Data Type: float64Type Casting with astype()
The astype() method allows you to explicitly convert an array’s data type to another. This is useful when performing operations that require consistent data types.
Example: Type Casting
# Create a float array
float_array = np.array([1.5, 2.8, 3.9], dtype='float64')
# Convert to integer
int_array = float_array.astype('int32')
print("Original Array:", float_array)
print("Converted Array:", int_array)Output:
Original Array: [1.5 2.8 3.9]
Converted Array: [1 2 3]Inspecting Data Types
Use the dtype attribute to inspect an array’s data type.
array = np.array([10, 20, 30], dtype='int32')
print("Data Type:", array.dtype) # Output: int32Why Use NumPy Data Types?
- Efficiency: NumPy types are more memory-efficient than Python’s native types.
- Performance: Operations on NumPy types are faster.
- Control: Enables precise control over memory and computations.
Try It Yourself
Problem 1: Create Arrays with Different Data Types
Create three arrays with int32, float64, and bool_ data types. Print their values and data types.
Show Code
import numpy as np
int_array = np.array([1, 2, 3], dtype='int32')
float_array = np.array([1.1, 2.2, 3.3], dtype='float64')
bool_array = np.array([True, False, True], dtype='bool_')
print("Integer Array:", int_array, "| Data Type:", int_array.dtype)
print("Float Array:", float_array, "| Data Type:", float_array.dtype)
print("Boolean Array:", bool_array, "| Data Type:", bool_array.dtype)Problem 2: Type Casting
Create an array with floating-point numbers and convert it to integers using astype(). Print both the original and converted arrays.
Show Code
import numpy as np
float_array = np.array([10.5, 20.8, 30.2], dtype='float64')
int_array = float_array.astype('int32')
print("Original Array:", float_array, "| Data Type:", float_array.dtype)
print("Converted Array:", int_array, "| Data Type:", int_array.dtype)