NumPy (Part 2): Array indexing, slicing, and operations
Following our Introduction to NumPy arrays, this article explores NumPy (Part 2): Array indexing, slicing, and operations. We'll learn how to access and manipulate data within NumPy arrays and how to perform mathematical operations on them.
📚 Prerequisites
- Understanding of NumPy arrays.
🎯 Article Outline: What You'll Master
- ✅ Array Indexing: Accessing single elements.
- ✅ Array Slicing: Accessing subarrays.
- ✅ Boolean Indexing: Selecting elements based on a condition.
- ✅ Array Math: Performing element-wise operations.
🧠 Section 1: The Core Concepts of Array Manipulation
NumPy offers more versatile ways to index and slice arrays than Python lists. You can use integer indexing, slicing, and boolean indexing to select elements from an array. NumPy also allows for efficient element-wise mathematical operations.
💻 Section 2: Deep Dive - Implementation and Walkthrough
import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
# Slicing
# Get the first two rows and columns 1 and 2
b = a[:2, 1:3]
# Boolean indexing
# Find elements greater than 5
bool_idx = (a > 5)
print(a[bool_idx]) # [ 6 7 8 9 10 11 12]
# Array math
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
# Elementwise sum
print(x + y)
# Elementwise difference
print(np.subtract(x, y))
# Elementwise product
print(x * y)
# Elementwise division
print(np.divide(x, y))
# Elementwise square root
print(np.sqrt(x))
💡 Conclusion & Key Takeaways
You've learned how to index, slice, and perform mathematical operations on NumPy arrays. These are fundamental skills for any data scientist working with Python.
Let's summarize the key takeaways:
- NumPy provides powerful and flexible indexing and slicing capabilities.
- Boolean indexing is a convenient way to select elements based on a condition.
- NumPy allows for fast, vectorized mathematical operations on arrays.
➡️ Next Steps
In the next article, "Pandas (Part 1): Introduction to Series and DataFrames", we will move on to Pandas, the primary library for data manipulation and analysis in Python.
Glossary
- Indexing: Accessing elements of an array.
- Slicing: Accessing subarrays of an array.
- Vectorization: Performing operations on entire arrays rather than individual elements.