First as always we must import numpy
:
import numpy as np
Let's create ourselves an array as before and check its shape.
a = np.arange(6)
print("a", a, ", shape:", a.shape)
We can change the shape of the array by modifying the shape directly, though this requires that the size
of the array remains the same.
a.shape = (3,2)
print(a)
What is the difference between reshape and resize?
mat = np.arange(6)
print(mat)
mat1 = np.reshape(mat, (3, 2))
print(mat1)
mat1.base is mat
Reshape creates a view of the object which has the shape specified in the function.
# Or can alter the size and shape of the array with
# resize(). May copy/pad depending on shape.
print(mat)
mat2 = np.resize(mat, (3, 2))
print(mat1)
mat2.base is mat # can also check this using id()
Ressize creates a copy of the object which has the shape specified in the function.
Fancy indexing allows us to select elements from an existing array using pairs of lists which specify the 'rows' and 'columns' that we want to select. In this case numpy
creates a copy.
p = np.array([[0, 1, 2],[3, 4, 5],
[6, 7, 8],[9, 10, 11]])
print(p)
Let's now create two sets of indices and make our new selection
rows = [0,0,3,3] # indices for rows
cols = [0,2,0,2] # indices for columns
q=p[rows,cols]
print(q)
Finally we can modify one of the arrays, print them and verify that the new array is not a view on the original array.
# ... check if a is a view or a copy
q[0]=1000
print(q)
print(p)
q.base is p