Geek Slack

Learn Numerical Python
About Lesson


NumPy Splitting Arrays


NumPy Splitting Arrays

Splitting arrays in NumPy allows you to divide an array into multiple sub-arrays. This is useful for various data manipulation tasks. NumPy provides several functions to split arrays.

Splitting Arrays with split()

The numpy.split() function splits an array into multiple sub-arrays as specified.

Example: Splitting a 1-D Array

import numpy as np

# Creating a 1-D array
arr = np.array([1, 2, 3, 4, 5, 6])

# Splitting the array into 3 sub-arrays
result = np.split(arr, 3)
print(result)
# Output: [array([1, 2]), array([3, 4]), array([5, 6])]

Example: Splitting a 2-D Array

import numpy as np

# Creating a 2-D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

# Splitting the array into 2 sub-arrays along axis 0
result = np.split(arr, 2)
print(result)
# Output:
# [array([[1, 2, 3],
#        [4, 5, 6]]), array([[ 7,  8,  9],
#        [10, 11, 12]])]

Horizontal Split

The numpy.hsplit() function splits an array into multiple sub-arrays horizontally (column-wise).

Example: Horizontal Split

import numpy as np

# Creating a 2-D array
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

# Splitting the array into 2 sub-arrays horizontally
result = np.hsplit(arr, 2)
print(result)
# Output:
# [array([[1, 2],
#        [5, 6]]), array([[3, 4],
#        [7, 8]])]

Vertical Split

The numpy.vsplit() function splits an array into multiple sub-arrays vertically (row-wise).

Example: Vertical Split

import numpy as np

# Creating a 2-D array
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

# Splitting the array into 2 sub-arrays vertically
result = np.vsplit(arr, 2)
print(result)
# Output:
# [array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]

Depth Split

The numpy.dsplit() function splits an array into multiple sub-arrays along the third axis (depth).

Example: Depth Split

import numpy as np

# Creating a 3-D array
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

# Splitting the array into 3 sub-arrays along the depth
result = np.dsplit(arr, 3)
print(result)
# Output:
# [array([[[ 1],
#         [ 4]],
#
#        [[ 7],
#         [10]]]), array([[[ 2],
#         [ 5]],
#
#        [[ 8],
#         [11]]]), array([[[ 3],
#         [ 6]],
#
#        [[ 9],
#         [12]]])]

Conclusion

Splitting arrays in NumPy is an essential operation for data manipulation. Whether you’re splitting arrays horizontally, vertically, or along the depth, NumPy provides a variety of functions to efficiently divide arrays into sub-arrays.

Join the conversation