Labs ICT
Pro Login

Stacking & Splitting

Combining and breaking apart arrays.

Stacking & Splitting

Stacking and splitting are like building blocks. Think of it like combining data from different sources or breaking a large dataset into chunks for processing.

Vertical Stack (vstack)

np.vstack() stacks arrays vertically (row-wise).


import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

vertical = np.vstack((a, b))
print(f"Vertical stack:\n{vertical}")
    

This creates a 2D array by stacking a and b as rows.

Horizontal Stack (hstack)

np.hstack() stacks arrays horizontally (column-wise).


import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

horizontal = np.hstack((a, b))
print(f"Horizontal stack: {horizontal}")
    

Here is the thing - for 1D arrays, hstack just concatenates them.

Splitting Arrays

np.split() divides arrays into equal parts.


import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
parts = np.split(arr, 3)
print(f"Split into 3: {parts}")
    

Each part is a sub-array. You can also specify split points manually.

One thing that confused me at first was the difference between vstack and hstack. Remember: vstack adds rows, hstack adds columns.

Try it Yourself →

Key Takeaways

  • np.vstack() stacks arrays vertically (adds rows)
  • np.hstack() stacks arrays horizontally (adds columns)
  • np.split() divides arrays into equal parts
  • These are essential for data manipulation