Wednesday, December 25, 2024
Google search engine
HomeLanguagesJoining NumPy Array

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. 

Syntax:

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.

Python3




import numpy as np
  
array_1 = np.array([1, 2])
array_2 = np.array([3, 4])
  
array_new = np.concatenate((array_1, array_2))
print(array_new)


Output: 

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

Python3




import numpy as np
  
array_1 = np.array([[1, 2], [3, 4]])
array_2 = np.array([[5, 6], [7, 8]])
  
array_new = np.concatenate((array_1, array_2), axis=1)
print(array_new)


Output:

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

Syntax:

numpy.stack(arrays, axis=0)

The following code demonstrates the use of numpy.stack().

Python3




import numpy as np
  
array_1 = np.array([1, 2, 3, 4])
array_2 = np.array([5, 6, 7, 8])
  
array_new = np.stack((array_1, array_2), axis=1)
print(array_new)


Output:

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

Syntax:

numpy.block(arrays)

The following example explains the working of numpy.block().

Python3




import numpy as np
  
block_1 = np.array([[1, 1], [1, 1]])
block_2 = np.array([[2, 2, 2], [2, 2, 2]])
block_3 = np.array([[3, 3], [3, 3], [3, 3]])
block_4 = np.array([[4, 4, 4], [4, 4, 4], [4, 4, 4]])
  
block_new = np.block([
    [block_1, block_2],
    [block_3, block_4]
])
  
print(block_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]]

In this example, we assembled a block matrix( block_new ) from 4 separate 2-d arrays (block_1,block_2,block_3,block_4 ).

RELATED ARTICLES

Most Popular

Recent Comments