Joining NumPy Array
NumPy provides various functions to combine arrays. In this article, we will discuss some of the major ones.
Method 1: Using numpy.concatenate()
The concatenate function in NumPy joins two or more arrays along a specified axis.
numpy.concatenate((array1, array2, ...), axis=0)
The first argument is a tuple of arrays we intend to join and the second argument is the axis along which we need to join these arrays. Check out the following example showing the use of numpy.concatenate.
[1 2 4 5]
By default, the value of the axis is set to 0. You can change it by specifying a value for the axis in the second argument. The following code joins two arrays along rows.
[[1 2 5 6] [3 4 7 8]]
Method 2: Using numpy.stack()
The stack() function of NumPy joins two or more arrays along a new axis.
The following code demonstrates the use of numpy.stack().
[[1 5] [2 6] [3 7] [4 8]]
The arrays are joined along a new axis.
Method 3: numpy.block()
numpy.block is used to create nd-arrays from nested blocks of lists.
The following example explains the working of numpy.block().
[[1 1 2 2 2] [1 1 2 2 2] [3 3 4 4 4] [3 3 4 4 4] [3 3 4 4 4]]
In this example, we assembled a block matrix( block_new ) from 4 separate 2-d arrays (block_1,block_2,block_3,block_4 ).
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course