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.
Divide the 2-D array into three 2-D arrays.
import numpy as np arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]) 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.
Divide the 2-D array into three separate 2-D arrays.
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]) 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).
Divide the 2-D array into three 2-D arrays along the rows.
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]) newarr = np.array_split(arr, 3, axis=1) print(newarr) |
An alternative solution is to use hsplit()
, which is the opposite of hstack()
.
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([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]) newarr = np.hsplit(arr, 3) print(newarr) |