Join a sequence of Numpy arrays with stack()

To join a sequence of arrays, use the numpy.stack() method in Python Numpy. The function returns the stacked array has one more dimension than the input arrays. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

The out parameter, if provided, the destination to place the result. The shape must be correct, matching that of what stack would have returned if no out argument were specified.

Steps

At first, import the required library −

import numpy as np

Creating two numpy arrays using the array() method. We have inserted elements of int type −

arr1 = np.array([49, 76, 61, 82, 69, 29])
arr2 = np.array([40, 60, 89, 55, 32, 98])

Display the arrays −

print("Array 1...
", arr1) print("
Array 2...
", arr2)

Get the type of the arrays −

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

Get the dimensions of the Arrays −

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

Get the shape of the Arrays −

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

To join a sequence of arrays, use the numpy.stack() method in Python Numpy −

print("
Result (stack)...
",np.stack((arr1, arr2)))

Example

import numpy as np

# Creating two numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([49, 76, 61, 82, 69, 29])
arr2 = np.array([40, 60, 89, 55, 32, 98])

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To join a sequence of arrays, use the numpy.stack() method in Python Numpy print("
Result (stack)...
",np.stack((arr1, arr2)))

Output

Array 1...
[49 76 61 82 69 29]

Array 2...
[40 60 89 55 32 98]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(6,)

Our Array 2 Shape...
(6,)

Result (stack)...
[[49 76 61 82 69 29]
[40 60 89 55 32 98]]

Updated on: 18-Feb-2022

188 Views