================ by Jawad Haider
01 - Numpy Indexing and Selection¶
- 1 NumPy Indexing and Selection
- 1.1 Bracket Indexing and Selection
- 1.2 Broadcasting
- 1.3 Indexing a 2D array (matrices)
- 1.4 More Indexing Help
- 1.5 Conditional Selection
- 2 Great Job! Thats the end of this part.
NumPy Indexing and Selection¶
In this lecture we will discuss how to select elements or groups of elements from an array.
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Bracket Indexing and Selection¶
The simplest way to pick one or some elements of an array looks very similar to python lists:
8
array([1, 2, 3, 4])
array([0, 1, 2, 3, 4])
Broadcasting¶
NumPy arrays differ from normal Python lists because of their ability to broadcast. With lists, you can only reassign parts of a list with new parts of the same size and shape. That is, if you wanted to replace the first 5 elements in a list with a new value, you would have to pass in a new 5 element list. With NumPy arrays, you can broadcast a single value across a larger set of values:
array([100, 100, 100, 100, 100, 5, 6, 7, 8, 9, 10])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
array([0, 1, 2, 3, 4, 5])
array([99, 99, 99, 99, 99, 99])
Now note the changes also occur in our original array!
array([99, 99, 99, 99, 99, 99, 6, 7, 8, 9, 10])
Data is not copied, it’s a view of the original array! This avoids memory problems!
array([99, 99, 99, 99, 99, 99, 6, 7, 8, 9, 10])
Indexing a 2D array (matrices)¶
The general format is arr_2d[row][col] or arr_2d[row,col]
. I recommend
using the comma notation for clarity.
array([[ 5, 10, 15],
[20, 25, 30],
[35, 40, 45]])
array([20, 25, 30])
20
20
array([[10, 15],
[25, 30]])
array([35, 40, 45])
array([35, 40, 45])
More Indexing Help¶
Indexing a 2D matrix can be a bit confusing at first, especially when you start to add in step size. Try google image searching NumPy indexing to find useful images, like this one:
Conditional Selection¶
This is a very fundamental concept that will directly translate to pandas later on, make sure you understand this part!
Let’s briefly go over how to use brackets for selection based off of comparison operators.
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
array([False, False, False, False, True, True, True, True, True,
True])
array([False, False, False, False, True, True, True, True, True,
True])
array([ 5, 6, 7, 8, 9, 10])
array([ 3, 4, 5, 6, 7, 8, 9, 10])
array([ 3, 4, 5, 6, 7, 8, 9, 10])
Great Job! Thats the end of this part.¶
Don't forget to give a star on github and follow for more curated Computer Science, Machine Learning materials