Array Operations
Discover the power of vectorization, broadcasting, and universal functions (ufuncs) in NumPy.
Discover the power of vectorization, broadcasting, and universal functions (ufuncs) in NumPy. This hands-on tutorial focuses on practical implementation of array operations concepts.
Module 4: Array Operations
The true power of NumPy lies in its ability to perform high-speed computations on entire arrays without writing single for loops. This is called Vectorization.
Lesson 8: Arithmetic Operations
Element-wise Operations
Arithmetic operators (+, -, *, /) applied to arrays perform operations element by element.
Scalar vs Array Operations
- Scalar: Adding a single number to an array applies it to every element.
- Array-Array: Adding two arrays of the same shape adds corresponding elements.
Broadcasting Rules
What if the shapes are different? NumPy uses Broadcasting to "stretch" the smaller array to match the larger one, provided they are compatible.
- The axes must match exactly, OR
- One of the axes must be 1.
Lesson 9: Mathematical Functions
NumPy provides Universal Functions (ufuncs) that operate efficiently on arrays.
Common ufuncs:
np.sqrt(arr): Square root.np.exp(arr): Exponential.np.log(arr): Natural logarithm.np.sin(arr),np.cos(arr): Trigonometric functions.
Lesson 10: Aggregations
Aggregations reduce an array to a single value (or a lower-dimensional array).
Essential Aggregates:
np.sum(),np.mean(),np.median()np.min(),np.max()np.std(),np.var()(Standard deviation and variance)
Axis-based Operations
You can perform these along specific axes:
axis=0: Vertical (column-wise).axis=1: Horizontal (row-wise).
Assignment: Statistical Analysis
Given an array of student marks: [78, 92, 45, 88, 56, 91, 74].
Challenge: Find the mean, detect if anyone scored above 90 (using np.max()), and find the index of the highest score using np.argmax().
Quiz
Question 1 of 5What is broadcasting in NumPy?
Key Takeaways
✅ Vectorization replaces slow loops with fast, internal C-code.
✅ Broadcasting allows math between arrays of different (but compatible) sizes.
✅ Use axis parameters to aggregate data specifically by row or column.