1-D Array
Indexing
Use bracket notation [ ] to get the value at a specific index. Remember that indexing starts at 0.
import numpy as np
a=np.arange(12)
a
# start from index 0
a[0]
# the last element
a[-1]
Output:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
0
11
Slicing
Use :
to indicate a range.
array[start:stop]
A second :
can be used to indicate step-size.
array[start:stop:stepsize]
Leaving
start
or stop
empty will default to the beginning/end of the array.
a[1:4]
a[-4:]
a[-5::-2] #starting 5th element from the end, and counting backwards by 2 until the beginning of the array is reached
Output:
array([1, 2, 3, 4])
array([ 8, 9, 10, 11])
array([7, 5, 3, 1])
Multidimensional Array
r = np.arange(36)
r.resize((6, 6))
r
Output:
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]])
Use bracket notation to index:
array[row, column]
and use : to select a range of rows or columns
r[2, 2]
r[3, 3:6]
r[:2, :-1]#selecting all the rows up to (and not including) row 2, and all the columns up to (and not including) the last column
r[-1, ::2]#selecting the last row, and only every other element
Output:
14
array([21, 22, 23])
array([[ 0, 1, 2, 3, 4],
[ 6, 7, 8, 9, 10]])
array([30, 32, 34])
We can also select nonadjacent elements by
r[[2,3],[4,5]]
Output:
array([16, 23])
Conditional Indexing
r[r > 30]
Output:
array([31, 32, 33, 34, 35])
Note that if you change some elements in the slice of an array, the original array will also be change. You can see the following example:
r2 = r[:3,:3]
print(r2)
print(r)
r2[:] = 0
print(r2)
print(r)
Output:
[[ 0 1 2]
[ 6 7 8]
[12 13 14]]
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[ 0 0 0 3 4 5]
[ 0 0 0 9 10 11]
[ 0 0 0 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
To avoid this, use r.copy
to create a copy that will not affect the original array.
r_copy = r.copy()
print(r_copy, '\n')
r_copy[:] = 10
print(r_copy, '\n')
print(r)
Output:
[[ 0 0 0 3 4 5]
[ 0 0 0 9 10 11]
[ 0 0 0 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
[[10 10 10 10 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]]
[[ 0 0 0 3 4 5]
[ 0 0 0 9 10 11]
[ 0 0 0 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]