Stacking & Splitting Arrays in NumPy (hstack, vstack, split)

๐Ÿ“Œ Introduction

When working with datasets, you often need to:

  • Combine multiple arrays
  • Split arrays into parts

With NumPy, this becomes very easy using stacking and splitting functions.


๐Ÿ” Why Use Stacking & Splitting?

They help you:

  • Merge datasets
  • Divide data for training/testing
  • Organize data efficiently

๐Ÿงช Example Arrays

import numpy as npa = np.array([1, 2, 3])
b = np.array([4, 5, 6])

โžก๏ธ 1. Horizontal Stack (hstack())

print(np.hstack((a, b)))

๐Ÿ‘‰ Output:

[1 2 3 4 5 6]

โœ” Combines arrays side by side


โฌ‡๏ธ 2. Vertical Stack (vstack())

print(np.vstack((a, b)))

๐Ÿ‘‰ Output:

[[1 2 3]
[4 5 6]]

โœ” Combines arrays row-wise


๐Ÿ“ 3. Column Stack (column_stack())

print(np.column_stack((a, b)))

๐Ÿ‘‰ Output:

[[1 4]
[2 5]
[3 6]]

โœ‚๏ธ 4. Splitting Arrays (split())

arr = np.array([1, 2, 3, 4, 5, 6])print(np.split(arr, 3))

๐Ÿ‘‰ Output:

[array([1, 2]), array([3, 4]), array([5, 6])]

โœ” Splits array into equal parts


โš ๏ธ Important Rule

Array must be evenly divisible when using split().

๐Ÿ‘‰ Otherwise โ†’ error โŒ


๐Ÿ”„ 5. Split 2D Arrays

arr = np.array([[1,2],[3,4],[5,6]])print(np.vsplit(arr, 3))

โšก Why Use NumPy?

Using NumPy:

  • Fast operations
  • Easy data manipulation
  • Supports large datasets

๐Ÿ“ฆ Real-World Use Case

# Combine features
feature1 = np.array([1,2,3])
feature2 = np.array([4,5,6])data = np.column_stack((feature1, feature2))
print(data)

โœ” Used in:

  • Machine learning datasets
  • Data preprocessing

๐Ÿ”— Works with Other Libraries

Stacking & splitting are used in:

  • Pandas
  • Scikit-learn
  • TensorFlow

๐Ÿ“Š Summary Table

FunctionDescription
hstack()Horizontal combine
vstack()Vertical combine
column_stack()Column-wise combine
split()Split array

๐Ÿง  Pro Tips

  • Use column_stack() for features
  • Use split() carefully (equal parts only)
  • Combine stacking with reshaping

๐Ÿ”š Conclusion

Stacking and splitting in NumPy make data handling flexible and efficient.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *