/Curriculum/IntermediateArray Manipulation

22. NumPy Splitting ArraysIntermediate

Divide arrays with split(), array_split(), vsplit(), and hsplit().

12 mins

Concept Overview

Splitting divides an array into multiple smaller sub-arrays along an axis. `np.array_split` allows unequal division without raising errors.

Hardware Mental Model

Splitting is slicing a loaf of bread into equal sandwich portions or dividing a deck of cards among players.

Key Concepts (1)Click snippet to load in editor

`np.split()` requires elements to divide equally. `np.array_split()` handles unequal splits gracefully by adjusting partition sizes.

train, val, test = np.array_split(data, 3)

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:np.split(np.arange(10), 3) # ValueError: cannot divide 10 by 3 equally
✓ Correct:np.array_split(np.arange(10), 3)

`np.split` throws an error if size is not divisible. Use `np.array_split` for uneven division.

Pro Tip: Use `array_split` when data lengths may vary dynamically.

📌 Quick Revision

Core takeaway points from this topic
`np.split(arr, N)`: Splits into N equal parts (raises error if indivisible).
`np.array_split(arr, N)`: Splits into N parts, allowing unequal sizes.
`np.vsplit()` & `np.hsplit()`: Specialized 2D vertical and horizontal splitters.
Editor: 22. NumPy Splitting Arrays
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Split 6 Elements into 2 Sub-arrays

Create `arr = np.array([10, 20, 30, 40, 50, 60])`, split into 2 parts with `np.split(arr, 2)`, and print part 0.

Expected Output Target:[10 20 30]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state