How To Join Multiple NumPy Array

Introduction:

Hello people! In this Tutorial we are going to learn about how to join multiple NumPy Array. Joining means putting contents of two or more arrays in a single array. NumPy provides various functions to combine arrays. Knowing how to work with NumPy arrays is an important skill as you progress in data science in Python. Because NumPy arrays can be 1 dimensional or 2 dimensional, it is important to understand the many different ways in which to join NumPy arrays. In this article, we will discuss some of the major functions.

  • numpy.concatenate
  • numpy.stack
  • numpy.block

Using numpy.concatenate() :

The concatenate function in NumPy joins two or more arrays along specified axis.

Syntax:

numpy.concatenate((arr1, arr2, ...), axis=0)

Code:

import numpy as np
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
arr_new = np.concatenate((arr1, arr2))
print(arr_new)

Output:

[1 2 4 5]

The value of axis is set to 0.We can change it by specifying for the axis in the second argument. The following code joins two arrays along rows.

Code:

import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[7, 8], [9, 0]])
arr_new = np.concatenate((arr1, arr2), axis=1)
print(arr_new)

Output:

[[1 2 7 8] [3 4 9 0]]

Using numpy.stack():

The stack function in NumPy joins two or more arrays along new axis.

Syntax:

numpy.stack(arrays, axis=0)

Code:

import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([6, 7, 8, 9])
arr_new = np.stack((arr1, arr2, axis=1)
print(arr_new)

Output:

[[1 6]
 [2 7]
 [3 8]
 [4 9]]

Using numpy.block():

The Block function in NumPy is used to create nd-arrays from nested blocks of lists.

Syntax:

numpy.block(arrays)

import numpy as np
b1 = np.array([[1, 1], [1, 1]])
b2 = np.array([[2, 2, 2], [2, 2, 2]])
b3 = np.array([[3, 3], [3, 3], [3, 3]])
b4 = np.array([[4, 4, 4], [4, 4, 4], [4, 4, 4]])
b_new = np.block([b1, b2], [b3, b4]])
print(b_new)

Output:

[[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]]

Conclusion:

In this tutorial, we have learnt how to join or concatenate NumPy arrays. Then we learned how to use concatenate() function to join arrays along different axes. Finally, we also learned about NumPy.stack() and Block() functions .

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top