Numpy split() Function



The Numpy split() Function divides an array into multiple subarrays along a specified axis. It can split the array into equal-sized subarrays if given an integer or at specified indices if given a list.

This function is particularly useful for breaking down data into smaller chunks for easier manipulation and analysis.

Syntax

The syntax for the Numpy split() function is as follows −

numpy.split(ary, indices_or_sections, axis=0)

Parameters

Below are the parameters of the Numpy split() Function −

  • ary(array_like): The input array to be split.
  • indices_or_sections(int or 1-D array): If an integer(N), the array will be divided into N equal sections. If an array, the values in the array indicate where to split the array.
  • axis(int, optional): The axis along which to split, default is 0 i.e. split along rows.

Return Value

This Function returns a list of sub-arrays resulting from the split.

Example 1

Following is the example of the shows Numpy split() Function which helps in splitting an array of 9 elements into 3 equal sub-arrays −

import numpy as np

# Create an array
arr = np.arange(9)
print("Original array:")
print(arr)

# Split the array into 3 equal parts
result = np.split(arr, 3)
print("\nSplit array into 3 equal parts:")
for i, sub_array in enumerate(result):
    print(f"Sub-array {i+1}:")
    print(sub_array)

Output

Original array:
[0 1 2 3 4 5 6 7 8]

Split array into 3 equal parts:
Sub-array 1:
[0 1 2]
Sub-array 2:
[3 4 5]
Sub-array 3:
[6 7 8]

Example 2

Here in this example we show how to split a 2D array into 2 sub-arrays along the columns i.e. axis=1 −

import numpy as np

# Create a 2D array
arr = np.arange(16).reshape(4, 4)
print("Original 2D array:")
print(arr)

# Split the 2D array into 2 sub-arrays along columns
result = np.split(arr, 2, axis=1)
print("\nSplit 2D array into 2 sub-arrays along columns:")
for i, sub_array in enumerate(result):
    print(f"Sub-array {i+1}:")
    print(sub_array)

Output

Original 2D array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

Split 2D array into 2 sub-arrays along columns:
Sub-array 1:
[[ 0  1]
 [ 4  5]
 [ 8  9]
 [12 13]]
Sub-array 2:
[[ 2  3]
 [ 6  7]
 [10 11]
 [14 15]]
numpy_array_manipulation.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy