02-Numpy Indexing and Selection
02-Numpy Indexing and Selection
___
[4]: #Show
arr
[5]: 8
1.2 Broadcasting
Numpy arrays differ from a normal Python list because of their ability to broadcast:
1
[8]: #Setting a value with index range (Broadcasting)
arr[0:5]=100
#Show
arr
#Show
arr
#Show slice
slice_of_arr
[12]: arr
Data is not copied, it’s a view of the original array! This avoids memory problems!
arr_copy
2
1.3 Indexing a 2D array (matrices)
The general format is arr_2d[row][col] or arr_2d[row,col]. I recommend usually using the
comma notation for clarity.
#Show
arr_2d
[16]: 20
[17]: 20
3
1.3.1 Fancy Indexing
Fancy indexing allows you to select entire rows or columns out of order,to show this, let’s quickly
build out a numpy array:
for i in range(arr_length):
arr2d[i] = i
arr2d
[23]: array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[ 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.],
[ 4., 4., 4., 4., 4., 4., 4., 4., 4., 4.],
[ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.],
[ 6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
[ 7., 7., 7., 7., 7., 7., 7., 7., 7., 7.],
[ 8., 8., 8., 8., 8., 8., 8., 8., 8., 8.],
[ 9., 9., 9., 9., 9., 9., 9., 9., 9., 9.]])
[24]: arr2d[[2,4,6,8]]
[24]: array([[ 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[ 4., 4., 4., 4., 4., 4., 4., 4., 4., 4.],
[ 6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
[ 8., 8., 8., 8., 8., 8., 8., 8., 8., 8.]])
[25]: array([[ 6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
[ 4., 4., 4., 4., 4., 4., 4., 4., 4., 4.],
[ 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[ 7., 7., 7., 7., 7., 7., 7., 7., 7., 7.]])
4
1.5 Selection
Let’s briefly go over how to use brackets for selection based off of comparison operators.
[30]: array([False, False, False, False, True, True, True, True, True, True],
dtype=bool)
[32]: bool_arr
[32]: array([False, False, False, False, True, True, True, True, True, True],
dtype=bool)
[33]: arr[bool_arr]
[34]: arr[arr>2]
[37]: x = 2
arr[arr>x]
2 Great Job!