20 August 2020
Code
# Import library
import numpy as np
# Create arrays
x = np.array([[1,2],[3,4]])
y = np.array([[10,20],[30,40]])
print("x:\n", x)
print('shape:',x.shape, '\n')
print("y:\n", y)
print('shape:',y.shape, '\n')
x:
[[1 2]
[3 4]]
shape: (2, 2)
y:
[[10 20]
[30 40]]
shape: (2, 2)
.
Using .stack():
# Stack
sh = np.stack((x,y), axis = 0)
sv = np.stack((x,y), axis = -1)
# Output
print("Stack (axis=0):\n", sh)
print('shape:',sh.shape, '\n')
print("Stack (axis=-1):\n", sv)
print('shape:',sv.shape, '\n')
Stack (axis=0):
[[[ 1 2]
[ 3 4]]
[[10 20]
[30 40]]]
shape: (2, 2, 2)
Stack (axis=-1):
[[[ 1 10]
[ 2 20]]
[[ 3 30]
[ 4 40]]]
shape: (2, 2, 2)
.
Using .hstack():
# Stack
hs = np.hstack((x,y))
# Output
print("hstack:\n", hs)
print('shape:',hs.shape, '\n')
hstack:
[[ 1 2 10 20]
[ 3 4 30 40]]
shape: (2, 4)
.
Using .vstack():
# Stack
vs = np.vstack((x,y))
# Output
print("vstack:\n", vs)
print('shape:',vs.shape, '\n')
vstack:
[[ 1 2]
[ 3 4]
[10 20]
[30 40]]
shape: (4, 2)
Any errors in code above?
Please send a message.