Numpy - Stacking and Splitting Arrays
Stacking and splitting arrays are common operations in NumPy that can be used to combine or separate arrays in various ways.
To stack arrays horizontally (i.e., column-wise), you can use the hstack
function, which takes a sequence of arrays as arguments and returns a single array with the arrays stacked horizontally. For example:
import numpy as np
# Create two arrays
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
# Stack the arrays horizontally
z = np.hstack((x, y))
print(z) # [1 2 3 4 5 6]
To stack arrays vertically (i.e., row-wise), you can use the vstack
function, which takes a sequence of arrays as arguments and returns a single array with the arrays stacked vertically. For example:
# Stack the arrays vertically
z = np.vstack((x, y))
print(z) # [[1 2 3]
# [4 5 6]]
To split an array into multiple smaller arrays, you can use the split
function, which takes an array and a sequence of indices or a boolean mask and returns a list of subarrays. For example:
# Create a one-dimensional array
x = np.array([1, 2, 3, 4, 5, 6])
# Split the array into three subarrays
y = np.split(x, [2, 4])
print(y) # [array([1, 2]), array([3, 4]), array([5, 6])]
You can also specify an axis along which to split the array using the axis
argument. For example:
# Create a two-dimensional array
x = np.array([[1, 2, 3], [4, 5, 6]])
# Split the array along the second axis
y = np.split(x, 2, axis=1)
print(y) # [array([[1], [4]]), array([[2], [5]]), array([[3], [6]])]