numpy.stack() function with example in python

Spread the love

numpy.stack() : This function help us to Join a sequence of arrays along a new axis.

Syntax: numpy.stack(arrays, axis=0, out=None)

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.

New in version 1.10.0.

arrays : sequence of array_like
Each array must have the same shape.

axis : int, optional
The axis in the result array along which the input arrays are stacked.

out : ndarray, optional
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.

stacked : ndarray
The stacked array has one more dimension than the input arrays.

import numpy as np x=np.array([1,2,3,4,5]) y= np.array([6,7,8,9,10]) z=np.stack((x, y)) print("\nwith out axis"z) z=np.stack((x, y), axis=1) print("\nwith axis 1",z)


with out axis [[ 1 2 3 4 5]
[ 6 7 8 9 10]]

with axis 1 [[ 1 6]
[ 2 7]
[ 3 8]
[ 4 9]
[ 5 10]]


Leave a Reply

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