Understanding NumPy Split Functions: A Comprehensive Guide

NumPy provides several functions for splitting arrays into multiple subarrays. These functions are incredibly useful for various data manipulation tasks, such as data preprocessing, machine learning, and numerical analysis. In this comprehensive guide, we'll explore the different split functions offered by NumPy, understand their syntax, usage, and explore practical examples.

Introduction to NumPy Split Functions

link to this section

NumPy offers several functions for splitting arrays into smaller arrays based on specific criteria. These functions allow you to split arrays along different axes, divide arrays into equal-sized subarrays, or partition arrays based on predefined conditions.

Types of Split Functions in NumPy

link to this section

1. numpy.split()

The numpy.split() function divides an array into multiple subarrays along a specified axis.

2. numpy.array_split()

The numpy.array_split() function is similar to numpy.split() , but it allows splitting arrays into multiple subarrays with uneven sizes.

3. numpy.hsplit() and numpy.vsplit()

These functions split arrays horizontally ( hsplit() ) or vertically ( vsplit() ), dividing arrays into subarrays along the specified axis.

Syntax of NumPy Split Functions

link to this section
# numpy.split() 
numpy.split(array, indices_or_sections, axis=0) 

# numpy.array_split() 
numpy.array_split(array, num_sections, axis=0) 

# numpy.hsplit() and numpy.vsplit() 
numpy.hsplit(array, indices_or_sections) 
numpy.vsplit(array, indices_or_sections) 

Examples of NumPy Split Functions

link to this section

Example 1: Splitting an array into three equal parts

import numpy as np 
arr = np.arange(12) 
result = np.split(arr, 3) 

Example 2: Splitting an array into uneven parts

import numpy as np 
arr = np.arange(10) 
result = np.array_split(arr, 3) 

Example 3: Splitting a 2D array vertically

import numpy as np 
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 
result = np.vsplit(arr, 3) 


link to this section

NumPy split functions are powerful tools for dividing arrays into smaller, manageable chunks. By understanding the syntax, usage, and examples provided in this guide, you'll be equipped to leverage these functions effectively in your data analysis and manipulation tasks using NumPy.