Array Manipulation
Array manipulation covers the techniques used to reshape and reorganize NumPy arrays - joining multiple arrays together, splitting one array into several, and changing its structure without altering the underlying data.
Joining Arrays
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate([a, b])) # [1 2 3 4 5 6]
print(np.vstack([a, b])) # stack vertically (rows)
print(np.hstack([a, b])) # stack horizontally (columns)
Splitting Arrays
import numpy as np
arr = np.arange(9) # [0 1 2 3 4 5 6 7 8]
parts = np.split(arr, 3)
print(parts) # [array([0,1,2]), array([3,4,5]), array([6,7,8])]
Transposing an Array
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.T)
# [[1 4]
# [2 5]
# [3 6]]
Adding and Removing Elements
import numpy as np
arr = np.array([1, 2, 3])
print(np.append(arr, [4, 5])) # [1 2 3 4 5]
print(np.insert(arr, 1, 99)) # [1 99 2 3]
print(np.delete(arr, 0)) # [2 3]
Reshaping and stacking operations are used constantly when preparing data for Machine Learning models, which often expect input arrays in a very specific shape, such as (number_of_samples, number_of_features).
Coming Up Next
Next, you'll learn how to read and write NumPy arrays to and from files, so your data can persist beyond a single session.