Array Indexing and Slicing in NumPy
Introducing Array Indexing and Slicing
Welcome back! Today, we are exploring Array Indexing and Slicing, two crucial concepts for data manipulation and processing. Utilizing Python's NumPy library, by the end of this lesson, you will be able to comfortably access and modify elements in a NumPy array.
Quick Refresher on NumPy Arrays
Let's quickly revisit NumPy arrays. A NumPy array is a powerful tool for numerical operations. Here's how we import NumPy and create a simple array:
Understanding Array Indexing
Array indexing lets us access an element in an array. It works just like with Python's lists! Python uses zero-based indexing, meaning the first element is at position 0. Here's how we access elements:
Note that [-1] gives us the last element, the same as with plain Python's lists!
Unwrapping Array Slicing
Array slicing lets us access a subset, or slice, of an array. The basic syntax for slicing in Python is array[start:stop:step].
Let's check this out:
As a reminder, stop is not included, so [1:4] gives us elements with indices 1, 2, 3. Also remember that we can skip any of arguments to make them default. Thus, [::2] specifies only the step parameter, so start and end are filled with the default value.
Let's recall the default values:
- start = 0
- end = len(array)
- step = 1
One important thing to know: if we modify elements in a sliced array, it also modifies the original array:
Indexing and Slicing in Multi-dimensional Arrays
Now, let's move to multi-dimensional arrays and try out these operations. We'll use a 2D array for illustration:
We use comma-separated indices for each dimension to get elements from 2D arrays. Below, we get the entire second row or the entire third column:
Slicing on multi-dimensional arrays is also simple. We can retrieve the first two rows and first two columns, for instance:
