Staking and Splitting Arrays
Combining arrays
Section titled “Combining arrays”np.concatenate
Section titled “np.concatenate”Concatenate along an axis.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate([a, b]))For 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.concatenate([a, b], axis=0)) # stack rows
print(np.concatenate([a, b], axis=1)) # stack colsnp.vstack and np.hstack
Section titled “np.vstack and np.hstack”import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.vstack([a, b]))
print(np.hstack([a, b]))np.stack (adds a new axis)
Section titled “np.stack (adds a new axis)”Unlike concatenate, stack creates a brand-new axis instead of joining along an existing one.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.stack([a, b], axis=0).shape) # (2, 3)
print(np.stack([a, b], axis=1).shape) # (3, 2)Splitting arrays
Section titled “Splitting arrays”np.split
Section titled “np.split”import numpy as np
arr = np.arange(10)
a, b = np.split(arr, [6])
print(a)
print(b)np.hsplit and np.vsplit
Section titled “np.hsplit and np.vsplit”import numpy as np
mat = np.arange(16).reshape(4, 4)
left, right = np.hsplit(mat, 2)
print(left)
print(right)
top, bottom = np.vsplit(mat, 2)
print(top)
print(bottom)flowchart LR A["Two arrays,
same shape"] --> B["np.vstack
join as rows"] A --> C["np.hstack
join as columns"] A --> D["np.stack
join on a NEW axis"] E["One matrix"] --> F["np.split / hsplit / vsplit
-> pieces back apart"]
Continue to: NumPy Random Module for generating reproducible random numbers and sampling.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Stack Two Rows
Section titled “Exercise 1 – Stack Two Rows”Exercise 2 – Split at an Index
Section titled “Exercise 2 – Split at an Index”Exercise 3 – New Axis with stack
Section titled “Exercise 3 – New Axis with stack”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading