A Numpy array can be divided into several arryas in Pyhton, and these kinds of operation are called splitting. In terms of row-wise or coloum-wise splitting, Numpy provide two operations in this respect,hsplit() and vsplit(). hsplit() will divide an original array into parts, with the option for how many parts to be splitted to. Similarly, vsplit() will split an array by column into specified parts number. The resulting arrays after these operations have same shapes.
#Import Numpy module
import numpy as np
#create an array of shape(8,4)
T = np.arange(32).reshape((8, 4))
T
#output
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]])
#horixontally splitting array into 2 parts
[T1, T2] = np.hsplit(T, 2)
T1
#output
array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13],
[16, 17],
[20, 21],
[24, 25],
[28, 29]])
T2
#output
array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15],
[18, 19],
[22, 23],
[26, 27],
[30, 31]])
#verticaly splitting array into 4 parts
[T3, T4,T5,T6] = np.vsplit(T, 4)
T3
#output
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
T4
#output
array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])
T5
#output
array([[16, 17, 18, 19],
[20, 21, 22, 23]])
T6
#output
array([[24, 25, 26, 27],
[28, 29, 30, 31]])
There is another function, split() perform similar job, but specifies which axis to split and at which index splitting is implemented.
#horizontally(axix=1) splitting array into 3 parts
[R1, R2, R3] = np.split(T, [1,3], axis=1)
R1
#output
array([[ 0],
[ 4],
[ 8],
[12],
[16],
[20],
[24],
[28]])
R2
#output
array([[ 1, 2],
[ 5, 6],
[ 9, 10],
[13, 14],
[17, 18],
[21, 22],
[25, 26],
[29, 30]])
R3
#output
array([[ 3],
[ 7],
[11],
[15],
[19],
[23],
[27],
[31]])
#vertically(axix=0) splitting array into 4 parts.
[R4,R5, R6,R7] = np.split(T, [2,4,7], axis=0)
R4
#output
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
R5
#output
array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])
R6
#output
array([[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27]])
R7
#output
array([[28, 29, 30, 31]])
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…