⚡ Array Operations
Array operations are where NumPy truly shines! Instead of writing loops to process each element individually, NumPy lets you perform mathematical operations on entire arrays at once. This is called vectorization, and it's both faster and more intuitive than traditional programming approaches.
Think of array operations as applying the same calculation to every element simultaneously - like having a super-powered calculator that works on thousands of numbers at once!
import numpy as np
# Array operations vs traditional loops
numbers = np.array([1, 2, 3, 4, 5])
# NumPy way: vectorized operations
squared = numbers ** 2
doubled = numbers * 2
added = numbers + 10
print(f"Original: {numbers}")
print(f"Squared: {squared}")
print(f"Doubled: {doubled}")
print(f"Added 10: {added}")
🎯 Why Array Operations Matter
Array operations are fundamental because they provide:
- Speed ⚡: Operations happen in optimized C code, not slow Python loops
- Simplicity 📝: Write
array * 2
instead of[x * 2 for x in array]
- Readability 👁️: Code looks like mathematical formulas
- Memory efficiency 💾: Operations happen in-place when possible
- Broadcasting 📡: Automatically handle arrays of different sizes
This is what makes NumPy the foundation of scientific computing in Python!
🔢 Basic Operations Preview
See how simple mathematical operations become with arrays:
import numpy as np
# Basic arithmetic operations
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(f"Array a: {a}")
print(f"Array b: {b}")
# Element-wise operations
print(f"a + b: {a + b}") # [11, 22, 33]
print(f"a - b: {a - b}") # [9, 18, 27]
print(f"a * b: {a * b}") # [10, 40, 90]
print(f"a / b: {a / b}") # [10.0, 10.0, 10.0]
# Operations with scalars
print(f"a * 2: {a * 2}") # [20, 40, 60]
print(f"a + 5: {a + 5}") # [15, 25, 35]
🎨 Element-wise Operations Preview
Every operation happens to corresponding elements:
import numpy as np
# Element-wise operations demonstration
temperatures_c = np.array([0, 25, 37, 100])
print(f"Celsius: {temperatures_c}")
# Convert to Fahrenheit: F = C * 9/5 + 32
temperatures_f = temperatures_c * 9/5 + 32
print(f"Fahrenheit: {temperatures_f}")
# Mathematical functions
angles = np.array([0, 30, 45, 90])
print(f"Angles (degrees): {angles}")
# Convert to radians and calculate sine
radians = angles * np.pi / 180
sine_values = np.sin(radians)
print(f"Sine values: {sine_values}")
📡 Broadcasting Preview
Broadcasting lets you combine arrays of different sizes intelligently:
import numpy as np
# Broadcasting example
matrix = np.array([[1, 2, 3], [4, 5, 6]]) # 2x3 matrix
vector = np.array([10, 20, 30]) # 1x3 vector
print(f"Matrix: \n{matrix}")
print(f"Vector: {vector}")
# Broadcasting: vector gets "expanded" to match matrix
result = matrix + vector
print(f"Matrix + Vector: \n{result}")
# Each row of matrix gets the vector added to it
print("Element-wise breakdown:")
print(f"Row 1: {matrix[0]} + {vector} = {matrix[0] + vector}")
print(f"Row 2: {matrix[1]} + {vector} = {matrix[1] + vector}")
📚 What You'll Learn in This Section
This section covers the essential array operation techniques:
- 🧮 Basic Mathematical Operations Master fundamental arithmetic operations (+, -, *, /) and how they work with arrays and scalars.
- ⚙️ Element-wise Operations Understand how operations apply to individual elements and explore mathematical functions.
- 📡 Broadcasting Rules Learn NumPy's powerful broadcasting system for working with arrays of different shapes.
🚀 Array Operations in Action
See how array operations solve real-world problems elegantly:
import numpy as np
print("💰 Real-world Array Operations")
print("=" * 30)
# Example 1: Sales analysis
monthly_sales = np.array([15000, 18000, 22000, 19000])
target = 20000
bonus_rate = 0.05
print(f"Monthly sales: {monthly_sales}")
print(f"Target: ${target:,}")
# Check which months exceeded target
exceeded_target = monthly_sales > target
print(f"Exceeded target: {exceeded_target}")
# Calculate bonuses (5% of amount over target)
excess = np.maximum(monthly_sales - target, 0) # No negative bonuses
bonuses = excess * bonus_rate
print(f"Bonuses: {bonuses}")
# Example 2: Data normalization
data = np.array([85, 92, 78, 96, 89])
print(f"\nOriginal scores: {data}")
# Normalize to 0-1 scale
normalized = (data - data.min()) / (data.max() - data.min())
print(f"Normalized (0-1): {normalized}")
# Standardize (mean=0, std=1)
standardized = (data - data.mean()) / data.std()
print(f"Standardized: {standardized}")
💡 Performance Benefits
Array operations are dramatically faster than Python loops:
🎯 Operation Types Overview
NumPy supports various types of operations:
Operation Type | Examples | Result |
---|---|---|
Arithmetic | + , - , * , / , ** | Element-wise math |
Comparison | < , > , == , != | Boolean arrays |
Logical | & , ` | , ~` |
Mathematical | np.sin() , np.sqrt() , np.log() | Function applications |
Statistical | np.mean() , np.sum() , np.std() | Summary statistics |
Conditional | np.where() , np.maximum() | Conditional operations |
🎯 Key Principles
Understanding these principles will help you master array operations:
import numpy as np
print("🎯 Key Array Operation Principles")
print("=" * 35)
# Principle 1: Element-wise by default
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(f"Element-wise: {a} * {b} = {a * b}")
# Principle 2: Broadcasting with scalars
print(f"Scalar broadcast: {a} * 10 = {a * 10}")
# Principle 3: Shape compatibility
matrix = np.array([[1, 2], [3, 4]])
vector = np.array([10, 20])
print(f"Shape compatibility: \n{matrix} + {vector} = \n{matrix + vector}")
# Principle 4: Functions are vectorized
angles = np.array([0, 0.5, 1.0]) * np.pi
print(f"Vectorized functions: sin({angles}) = {np.sin(angles)}")
# Principle 5: Operations return new arrays (usually)
original = np.array([1, 2, 3])
result = original * 2
print(f"Original unchanged: {original}")
print(f"New result: {result}")
🎯 Key Takeaways
🚀 What's Next?
Ready to dive into the power of array operations? Let's start with basic mathematical operations - the foundation of all numerical computing with NumPy.
Continue to: Basic Mathematical Operations
Time to compute at lightning speed! ⚡✨
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.