Lesson 3

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.

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:

Python`1import numpy as np 2 3arr = np.array([1, 2, 3, 4, 5]) 4print(arr) # array([1, 2, 3, 4, 5])`

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:

Python`1print(arr) # array([1, 2, 3, 4, 5]) 2print(arr[0]) # 1 3print(arr[2]) # 3 4print(arr[-1]) # 5`

Note that `[-1]`

gives us the last element, the same as with plain Python's lists!

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:

Python`1print(arr) # array([1, 2, 3, 4, 5]) 2print(arr[1:4]) # array([2, 3, 4]) 3print(arr[::2]) # array([1, 3, 5])`

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:

Python`1arr_slice = arr[1:4] 2arr_slice[1] = 10 3 4# Our original array changed too! 5print(arr) # array([1, 2, 10, 4, 5])`

Now, let's move to multi-dimensional arrays and try out these operations. We'll use a 2D array for illustration:

Python`1arr_multi = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 2print(arr_multi) 3# array([[1, 2, 3], 4# [4, 5, 6], 5# [7, 8, 9]])`

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:

Python`1print(arr_multi[0, 2]) # 3 2print(arr_multi[1]) # array([4, 5, 6]) 3print(arr_multi[:, 2]) # array([3, 6, 9])`

Slicing on multi-dimensional arrays is also simple. We can retrieve the first two rows and first two columns, for instance:

Python`1print(arr_multi[:2, :2]) 2# array([[1, 2], 3# [4, 5]])`

Great job! You've learned how to manipulate arrays in Python using `NumPy`

! Now, it's time to practice. Apply these concepts to different arrays and witness the magic in action! Happy coding! Stay tuned for our next session.