In the previous article, we saw how we could join two arrays in NumPy, but now we are going to see how to split an array into multiple sub-arrays. NumPy has built-in function called
Example
import numpy as np
arr = np.array(['a', 'b', 'c', 'd'])newarr = np.array_split(arr, 2)print(newarr)
We pass the array we want to split to the function while specifying the number to which we want spilt the array. After this the compiler will execute the program.
OUTPUT
In a case where the arrays have less elements than required elements, the compiler arranges the elements at end.
Example
import numpy as nparr = np.array(['a', 'b', 'c', 'd', 'e'])
newarr = np.array_split(arr, 3)print(newarr)
Splitting 2-D Arrays
We are still going to apply the same function
Example
import numpy as np
arr = np.array([['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']])newarr = np.array_split(arr,2)print(newarr)
The compiler splits the input array into 3 sub-different arrays given to it by array.split.
2-D arrays
OUTPUT
We can spit arrays vertically, horizontal or depth-wise. We do this using any of these functions below: hsplit(), vsplit() and dsplit(). These functions are found in NumPy The position is always specified after the spilt has occur.
Vertically spiting: we are going to use the function vsplit(). This functions splits array row-wise. After the spitting has occur, the resulting arrays is arranged in order row order.
Example
import numpy as np
a = np.arange(9).reshape(3, 3)print("The array {} gets splitted \vertically to form {} ".format(a, np.vsplit(a, 3)))
OUTPUT
Horizontal spiting: We are going use the hsplit(). The functions spits array column wise that is horizontally. After the splitting occurs, the resulting array is arranged in column order.
Example
import numpy as np
a = np.arange(9).reshape(3, 3)print("The array {} gets splitted \horizontally to form {} ".format(a, np.hsplit(a, 3)))
The array is passed to the spit function. After the spitting has occur, the position (orientation of the array) is then specified for the compiler to execute the program.
OUTPUT
Depth wise: we are going to spilt an array into sub-arrays along depth.
import numpy as np
a = np.arange(9).reshape(3, 3)print("The array {} gets splitted \depth-wise to form {} ".format(a, np.hsplit(a, 3)))
OUTPUT
We have come to the end of this session. I hope you found this guide useful. If so, do share it with others who are willing to learn NumPy and Python. If you have any questions related to this article, feel free to ask us in the comments section.
Comments
Post a Comment
Please do not enter any spam link in the comment box.