Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Numpy vsplit() Function



The Numpy vsplit() function is used to split an array into multiple sub-arrays along the vertical axis (axis 0). It is used for dividing a 2D array into smaller arrays row-wise. This function requires two arguments one is the array to split and the other one is number of sections to create.

For example, if we have a 2D array with shape (6, 4) and use np.vsplit(array, 3), it will return three sub-arrays, each with shape (2, 4).

This function raises a ValueError if the number of sections does not evenly divide the size of the specified axis.

Syntax

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

numpy.vsplit(array, indices_or_sections)

Parameters

Following is the syntax of Numpy vsplit() function −

  • ary(array_like): The input array to be split.
  • indices_or_sections: This parameter can be an integer indicating the number of equally shaped sub-arrays to create along the vertical axis or a 1-D array of sorted integers specifying the split points.

Return Value

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

Example 1

Following is the example of Numpy vsplit() function in which the array arr is split vertically into 2 equally shaped sub-arrays −

import numpy as np

# Create an array
arr = np.arange(16).reshape((4, 4))

# Split the array into 2 equal parts vertically
result = np.vsplit(arr, 2)

# Print the original array and the resulting sub-arrays
print("Original Array:")
print(arr)
print("\nAfter vsplitting into 2 parts:")
for sub_arr in result:
    print(sub_arr)

Output

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

After vsplitting into 2 parts:
[[0 1 2 3]
 [4 5 6 7]]
[[ 8  9 10 11]
 [12 13 14 15]]

Example 2

Below example shows how to use the hsplit() function handles indices that exceed array dimensions by creating empty arrays −

import numpy as np

# Create a 2D array with shape (4, 5)
arr = np.arange(20).reshape((4, 5))

# Split the array into 2 parts vertically
result = np.vsplit(arr, 2)

# Print the original array and the resulting sub-arrays
print("Original Array:")
print(arr)
print("\nAfter vsplitting into 2 parts:")
for sub_arr in result:
    print(sub_arr)

After execution of above code, we get the following result

Original Array:
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]

After vsplitting into 2 parts:
[[0 1 2 3 4]
 [5 6 7 8 9]]
[[10 11 12 13 14]
 [15 16 17 18 19]]
numpy_array_manipulation.htm
Advertisements