Splitting Arrays in NumPy
NumPy provides functions to split arrays into multiple sub-arrays. The main functions used for splitting are:
- split() - Splits an array into multiple sub-arrays.
- hsplit() - Splits an array horizontally (column-wise).
- vsplit() - Splits an array vertically (row-wise).
1. General Splitting (split)
The split() function divides an array into multiple sub-arrays based on the provided indices.
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) split_arr = np.split(arr, 3) print(split_arr)
Output:
[array([1, 2]), array([3, 4]), array([5, 6])]
2. Horizontal Splitting (hsplit)
The hsplit() function splits an array into sub-arrays along the second axis (columns).
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) hsplit_arr = np.hsplit(arr, 2) print(hsplit_arr)
Output:
[array([[1, 2], [5, 6]]), array([[3, 4], [7, 8]])]
3. Vertical Splitting (vsplit)
The vsplit() function splits an array into sub-arrays along the first axis (rows).
arr = np.array([[1, 2, 3], [4, 5, 6]]) vsplit_arr = np.vsplit(arr, 2) print(vsplit_arr)
Output:
[array([[1, 2, 3]]), array([[4, 5, 6]])]
Conclusion
Splitting arrays in NumPy helps break down large datasets into smaller segments. The split() function provides general splitting, hsplit() is used for horizontal splitting, and vsplit() is useful for vertical splitting.