NumPy provides various functions to combine arrays.
- concatenate
- stack
- block
Method 1: Using concatenate()
The concatenate function in NumPy joins two or more arrays along a specified axis.
Syntax:
numpy.concatenate((array1, array2, ...), axis=0)
Example:
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]
Method 2: Using stack()
The stack() function of NumPy joins two or more arrays along a new axis.
Syntax:
numpy.stack(arrays, axis=0)
Example:
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]]
Method 3: block()
numpy.block is used to create nd-arrays from nested blocks of lists.
Syntax:
numpy.block(arrays)
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]]