First as always we must import numpy
:
import numpy as np
a = np.array( [-1, 0, 1] )
print(a)
Mow let's assign the array we've created to another variable:
b = a
print("a", a)
print("b", b)
If we now modify a
what will happen to b
a[0]=2
print(a)
print(b)
When we assign b
to a
both variables point to the same object, (the same happens with lists!).
If we want to copy a numpy array we must explicitly call <ndarray>.copy()
:
c = np.ones( (3,3) )
d = c
e = c.copy()
print("c", c)
print("d", d)
print("e", e)
Now let's modify c
:
c[0][0]=10
print("c", c)
print("d", d)
print("e", e)
Basic indexing and slicing can be used to access array elements, as we know from lists:
# a[start:stop:stride] (not inclusive of stop)
x = np.arange(8)
print("x", x)
print("x[0:7:2]", x[0:7:2])
print("x[0::2]", x[0::2])
And as with lists negative indices are valid! Useful if you want to access from the end of the array
print(x[-1], x[-2], x[-3])
To access multidimensional arrays we can use multiple index subscripts, or we can use a tuple
.
# Basic indexing of a 3d array
m = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
print(c.shape)
# using subscripts
print("m[1][0][1]:", m[1][0][1])
# using a tuple
print("m[(1,0,1)]:", m[(1,0,1)])
# the whole thing
print(m)
We can access complete slices by leaving out indices or using elipses:
print(m[1])
print(m[1,0,...]) # can also use elipsis (3 dots)
# for missing indices
print(m[...,1,1]) # anywhere in indices
print(m[...,...,1]) # but only once