NumPy Arrays in Python
NumPy Arrays in Python
Example Syntax
arr = np.array([1, 2, 3]). This creates a 1D array. arr =
np.zeros((2, 3)) creates a 2x3 array of zeros.
Array Operations
Addition
Arrays can be added element-wise. The + operator
performs addition.
Subtraction
Arrays can be subtracted element-wise. The -
operator performs subtraction.
Statistical Functions
NumPy provides functions like np.mean(),
np.median(), and np.std(). These compute
statistical measures.
Indexing and Slicing
Accessing Elements Slicing Arrays
Array elements are accessed using their index. Slicing extracts a portion of an array. Use the colon ":"
Indexing starts at 0. to specify a range.
Example: arr[0] accesses the first element. Example: arr[1:5] gets elements from index 1 to 4.
Broadcasting
Different Shapes Compatibility Broadcasting Rules
Broadcasting allows Smaller arrays are "broadcast" Dimensions are compatible if
operations on arrays with to match the shape of larger they are equal or one of them
different shapes. arrays. Dimensions must be is 1. NumPy automatically
compatible. handles the expansion.
Reshaping and Transposing
Transposing Arrays
The transpose() method swaps rows
and columns. This is useful for matrix
Reshaping Arrays operations.
The reshape() method changes the
array's dimensions. It requires the Data Arrangement
same number of elements. These functions provide flexibility in
data arrangement. Reshape is for
rearranging data and transpose is for
changing the shape of the array.
Vectorization
Efficient Code
Vectorization replaces explicit loops with array operations.
Numerical Computations
Vectorized code is much faster than looped code. NumPy is optimized for
numerical computations.
Python Optimization
NumPy operations are implemented in C. This makes
them faster than standard Python loops.
Practical Applications