Python Stack (numpy)


The stack() function in Python can be used to stack data.

Stack translates to stack, that is, to stack data, the prototype function is:

stack(arrays, axis=0)

arrays can pass arrays and lists. axis is to operate on the data in the horizontal (row) direction or vertical (column) direction.

Note we talk about numpy.stack which joins a sequence of arrays along a new axis, not computer stack.

Related course: Complete Python Programming Course & Exercises

Stack example

The program below demonstrates the stack:

import numpy as np
a=[[1,2,3],
   [4,5,6]]
print("lista as follows:")
print(a)

print("axis=0")
c=np.stack(a,axis=0)
print(c)

print("axis=1")
c=np.stack(a,axis=1)
print(c)

The results are as follows.

Table a reads as follows.
[[1, 2, 3], [4, 5, 6]]
axis=0
[[1 2 3]
 [4 5 6]]
axis=1
[[1 4]
 [2 5]
 [3 6]]

With stack, you can convert a list to a numpy array, when axis=0, it is no different from using np.array(), but when axis=1, then you are doing the operation on the column direction for each row, that is, the column direction is combined, and the dimension of the matrix is changed from (2,3) to (3,2).

Let's look at another example.

import numpy as np

a=[[1,2,3,4],
   [5,6,7,8], 
   [9,10,11,12]]
print("lista as follows:")
print(a)

print("axis=0")
c=np.stack(a,axis=0)
print(c)

print("axis=1")
c=np.stack(a,axis=1)
print(c)

The results are as follows.

Table a reads as follows.

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
axis=0
[[1 2 3 4]
 [ 5 6 7 8]
 [ 9 10 11 12]]
axis=1
[[15 9]
 [ 2 6 10] 
 [ 3 7 11] 
 [ 4 8 12]]

By the same token, when axis=1 you remember to process each row against a column

hstack() function

Prototype: hstack(tup), the argument tup can be a tuple, a list, or a numpy array, returning an array that results in a numpy. Look at the code below to see what it means.

import numpy as np
a=[1,2,3]
b=[4,5,6]
print(np.hstack((a,b)))

Output: [1 2 3 4 5 6]

import numpy as np
a=[[1],[2],[3]]
b=[[4],[5],[6]]
print(np.hstack((a,b)))

Output.

 [[1 4]
 [2 5]
 [3 6]]

That is, stacking the data horizontally (in order of columns) h is horizontal in the horizontal direction, vstack is the opposite

vstack() function

Prototype: vstack(tup), the argument tup can be a tuple, a list, or a numpy array, returning an array that results in a numpy. Look at the code below to see what it means.

import numpy as np

a=[1,2,3]
b=[4,5,6]
print(np.vstack((a,b)))

Output.

[[1 2 3]
 [4 5 6]]

import numpy as np

a=[[1],[2],[3]]
b=[[4],[5],[6]]
print(np.vstack((a,b)))

Output.

[[1]
 [2]
 [3]
 [4]
 [5]
 [6]]

It's stacking the array vertically (in line order). v means vertical.