NumPy is a fundamental library for scientific computing in Python, providing powerful tools for working with numerical data. At the core of NumPy is the ndarray object, a multidimensional array that is optimized for efficient numerical operations.
Understanding NumPy Arrays
- Homogeneous Data: Unlike Python lists, NumPy arrays are homogeneous, meaning all elements must be of the same data type (e.g., integers, floats, strings).
- Multidimensional Structure: NumPy arrays can have any number of dimensions, from 1D vectors to higher-dimensional matrices.
- Efficient Storage: NumPy arrays are stored in contiguous memory blocks, allowing for efficient operations and faster execution times compared to Python lists.
- Broadcasting: NumPy’s broadcasting mechanism enables operations between arrays of different shapes, providing flexibility in calculations.
Creating NumPy Arrays
Direct Initialization:
Python
import numpy as np
# Create a 1D array
arr1d = np.array([1, 2, 3])
# Create a 2D array
arr2d = np.array([[1, 2], [3, 4]])
Using Array Creation Functions:
Python
# Create an array of zeros
zeros = np.zeros((2, 3))
# Create an array of ones
ones = np.ones((3, 4))
# Create an array of random values
random = np.random.rand(2, 2)
Accessing and Modifying Array Elements
Indexing:
Python
# Access an element
element = arr1d[0]
# Access a slice
slice = arr2d[1:3, 0:2]
Boolean Indexing:
Python
# Create a boolean mask
mask = arr1d > 2
# Extract elements based on the mask
result = arr1d[mask]
Array Attributes
- Shape: The dimensions of the array (e.g., (2, 3) for a 2×3 matrix).
- dtype: The data type of the elements in the array (e.g., int32, float64).
- ndim: The number of dimensions of the array.
- size: The total number of elements in the array.
Basic Array Operations
Arithmetic Operations:
Python
result = arr1d + arr2d
result = arr1d * 2
Matrix Operations:
Python
Matrix multiplication
result = np.dot(arr2d, arr2d.T)
Aggregation Functions:
Python
sum = np.sum(arr1d)
mean = np.mean(arr2d)
By understanding the fundamentals of NumPy arrays, you can effectively work with numerical data and perform various computations efficiently in Python.