NumPy Splitting Array

✂️ NumPy Splitting Arrays (Complete Guide)

Splitting arrays is the opposite of joining arrays — it divides one array into multiple smaller sub-arrays.

NumPy provides these main split methods:

array_split()
split()
hsplit()
vsplit()
dsplit()


✅ 1. np.array_split() (Most Flexible)

You can split an array into equal or unequal pieces.

import numpy as np

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

result = np.array_split(arr, 3)
print(result)

Output:

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

💡 If the array can’t be divided equally, it will automatically adjust.


❌ 2. np.split() (Strict Split)

split() only works if the array is split equally.

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

print(np.split(arr, 3))

Output:

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

But this is ❌ invalid:

np.split(arr, 4) # Error

✅ 3. Splitting 2D Arrays

arr = np.array([[1,2,3],[4,5,6],[7,8,9]])

result = np.array_split(arr, 3)
print(result)


Split along Columns (axis=1)

result = np.array_split(arr, 3, axis=1)
print(result)

🚀 Horizontal Split — hsplit()

Splits array column-wise.

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

print(np.hsplit(arr, 3))

Output:

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

🚀 Vertical Split — vsplit()

Splits array row-wise.

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

print(np.vsplit(arr, 2))

Output:

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

🚀 Depth Split — dsplit()

For 3D arrays.

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


📌 Summary Table

Method Works If Equal? Supports 1D 2D 3D
array_split() ❌ No
split() ✔ Yes
hsplit() ✔ Yes
vsplit() ✔ Yes
dsplit() ✔ Yes

🎯 Example Challenge

Split this array into 4 parts:

arr = np.arange(1,13).reshape(3,4)

print(np.array_split(arr, 4))

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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