Shape Manipulation & Reshape
Understanding shape
shapeshape tells the size of each dimension.
shape
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # (2, 3)shape
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # (2, 3)Reshape with .reshape().reshape()
Reshape changes the dimension layout without changing the data.
reshape
import numpy as np
arr = np.arange(1, 13) # 1..12
mat = arr.reshape(3, 4) # 3 rows, 4 cols
print(mat)reshape
import numpy as np
arr = np.arange(1, 13) # 1..12
mat = arr.reshape(3, 4) # 3 rows, 4 cols
print(mat)Using -1-1 (auto infer)
reshape-auto
import numpy as np
arr = np.arange(12)
mat = arr.reshape(3, -1)
print(mat.shape) # (3, 4)reshape-auto
import numpy as np
arr = np.arange(12)
mat = arr.reshape(3, -1)
print(mat.shape) # (3, 4)Flattening arrays
.ravel().ravel() (often a view)
ravel
import numpy as np
mat = np.array([[1, 2], [3, 4]])
flat = mat.ravel()
print(flat)ravel
import numpy as np
mat = np.array([[1, 2], [3, 4]])
flat = mat.ravel()
print(flat).flatten().flatten() (always copy)
flatten
import numpy as np
mat = np.array([[1, 2], [3, 4]])
flat = mat.flatten()
print(flat)flatten
import numpy as np
mat = np.array([[1, 2], [3, 4]])
flat = mat.flatten()
print(flat)Add or remove dimensions
np.newaxisnp.newaxis / NoneNone
Convert a 1D array into a column vector:
newaxis
import numpy as np
arr = np.array([1, 2, 3])
col = arr[:, None]
print(col)
print(col.shape) # (3, 1)newaxis
import numpy as np
arr = np.array([1, 2, 3])
col = arr[:, None]
print(col)
print(col.shape) # (3, 1)np.expand_dimsnp.expand_dims
expand
import numpy as np
arr = np.array([1, 2, 3])
arr2 = np.expand_dims(arr, axis=0)
print(arr2.shape) # (1, 3)expand
import numpy as np
arr = np.array([1, 2, 3])
arr2 = np.expand_dims(arr, axis=0)
print(arr2.shape) # (1, 3)np.squeezenp.squeeze (remove size-1 dims)
squeeze
import numpy as np
arr = np.array([[[1], [2], [3]]])
print(arr.shape) # (1, 3, 1)
print(np.squeeze(arr).shape) # (3,)squeeze
import numpy as np
arr = np.array([[[1], [2], [3]]])
print(arr.shape) # (1, 3, 1)
print(np.squeeze(arr).shape) # (3,)Transpose (swap axes)
For 2D:
transpose
import numpy as np
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(mat.T)transpose
import numpy as np
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(mat.T)Next
Continue to: Broadcasting in NumPy to learn how NumPy applies operations between different shapes.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
