Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy stack() Function



The Numpy stack() Function is used to join a sequence of arrays along a new axis. All input arrays must have the same shape.

This function is useful for combining arrays of the same shape along a specified dimension while creating a new dimension in the output array. For example, stacking two 2D arrays along a new axis creates a 3D array.

Syntax

The syntax for the Numpy stack() function is as follows −

numpy.stack(arrays, axis=0, out=None, *, dtype=None, casting='same_kind')

Parameters

  • arrays: These are the arrays you want to stack. All arrays must have the same shape.
  • axis: The axis along which the arrays will be stacked. It must be between 0 and the number of dimensions of the input arrays.
  • out: If provided, the destination to place the result. It should be of the appropriate shape and dtype.
  • dtype: If provided, the dtype to use for the resulting array.
  • casting: Controls what kind of data casting may occur.

Return Value

The stack() funcion returns the stacked array with one more dimension than the input arrays.

Example 1

Following is the basic example of using Numpy stack() Function. In this example the two 1-D arrays are stacked along a new axis, resulting in a 2-D array

import numpy as np

array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
stacked_array = np.stack((array1, array2))

print("Stacked Array:\n", stacked_array)

Output

Stacked Array:
 [[1 2 3]
  [4 5 6]]

Example 2

This is another example of using the stack() function, here in this example two 2-D arrays are stacked along axis 1 which results in a 3-D array −

import numpy as np

array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
stacked_array = np.stack((array1, array2), axis=1)

print("Stacked Array:\n", stacked_array)

Output

Stacked Array:
 [[[1 2]
   [5 6]]

  [[3 4]
   [7 8]]]

Example 3

Here in ths example two 3-D arrays are stacked along axis 2, resulting in a 4-D array −

import numpy as np

array1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
array2 = np.array([[[9, 10], [11, 12]], [[13, 14], [15, 16]]])
stacked_array = np.stack((array1, array2), axis=2)

print("Stacked Array:\n", stacked_array)

Output

Stacked Array:
 [[[[ 1  2]
   [ 9 10]]

  [[ 3  4]
   [11 12]]]


 [[[ 5  6]
   [13 14]]

  [[ 7  8]
   [15 16]]]]
numpy_array_manipulation.htm
Advertisements