Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Splitting 2-D Arrays

Apply the same syntax for splitting 2-D arrays by using the array_split() method, where you provide the array to divide and specify the desired number of splits.

Example

Divide the 2-D array into three 2-D arrays.

import numpy as np

arr = np.array([[12], [34], [56], [78], [910], [1112]])

newarr = np.array_split(arr, 3)

print(newarr)

The previous example returns three 2-D arrays. Now, let’s look at another example where each element in the 2-D arrays contains three elements.

Example

Divide the 2-D array into three separate 2-D arrays.

import numpy as np

arr = np.array([[123], [456], [789], [101112], [131415], [161718]])

newarr = np.array_split(arr, 3)

print(newarr)

The previous example yields three 2-D arrays. You can also specify the axis for the split, as the next example demonstrates, returning three 2-D arrays split along the rows (axis=1).

Example

Divide the 2-D array into three 2-D arrays along the rows.

import numpy as np

arr = np.array([[123], [456], [789], [101112], [131415], [161718]])

newarr = np.array_split(arr, 3, axis=1)

print(newarr)

An alternative solution is to use hsplit(), which is the opposite of hstack().

Example

Utilize the hsplit() method to divide the 2-D array into three 2-D arrays along the rows.

import numpy as np

arr = np.array([[123], [456], [789], [101112], [131415], [161718]])

newarr = np.hsplit(arr, 3)

print(newarr)