0
0
NumPydata~5 mins

np.split() for dividing arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.split() to break a big array into smaller parts. This helps us work with pieces of data separately.

You want to divide a list of daily temperatures into weeks.
You have a long list of sales numbers and want to analyze each quarter separately.
You want to split a dataset into training and testing parts for a machine learning model.
You want to process parts of an image separately by splitting its pixel array.
Syntax
NumPy
import numpy as np

# Split array into multiple sub-arrays
np.split(array, indices_or_sections, axis=0)

array is the original array you want to split.

indices_or_sections can be an integer (number of equal parts) or a list of indices where to split.

Examples
Splits the array into 3 equal parts.
NumPy
import numpy as np

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

# Split into 3 equal parts
parts = np.split(array, 3)
print(parts)
Splits the array at positions 2 and 4, creating 3 parts.
NumPy
import numpy as np

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

# Split at indices 2 and 4
parts = np.split(array, [2, 4])
print(parts)
Splitting an empty array returns empty arrays.
NumPy
import numpy as np

array = np.array([])

# Split empty array into 2 parts
parts = np.array_split(array, 2)
print(parts)
Splitting a single element array into 1 part returns the array itself.
NumPy
import numpy as np

array = np.array([10])

# Split single element array into 1 part
parts = np.split(array, 1)
print(parts)
Sample Program

This program creates an array of 12 numbers and splits it into 4 equal parts. It prints the original array and each part after splitting.

NumPy
import numpy as np

# Create an array of 12 numbers
numbers = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120])

print("Original array:", numbers)

# Split into 4 equal parts
split_parts = np.split(numbers, 4)

print("\nArray split into 4 parts:")
for index, part in enumerate(split_parts, start=1):
    print(f"Part {index}:", part)
OutputSuccess
Important Notes

Time complexity is O(n) because the array elements are copied into new arrays.

Space complexity is O(n) since new arrays are created for each part.

A common mistake is trying to split into parts that do not evenly divide the array length, which causes an error.

Use np.array_split() if you want to split into unequal parts without error.

Summary

np.split() breaks an array into smaller arrays at specified points or into equal parts.

It requires the array to be divisible evenly if using an integer number of parts.

Useful for dividing data into chunks for separate analysis or processing.