Table of contents
vstack() function and hatack() function
The vstack() function connects two arrays vertically.
The hatack() function concatenates two arrays horizontally.
When the array type is a one-dimensional array
Look at the code below:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# 竖直方向上连接
print(np.vstack((arr1, arr2)))
#水平方向上连接
print(np.hstack((arr1, arr2)))
The output result is:
[[1 2 3]
[4 5 6]]
[1 2 3 4 5 6]
When the array type is a two-dimensional array
The code shows:
import numpy as np
arr1 = np.array([[1, 2], [3, 4], [5, 6]])
arr2 = np.array([[7, 8], [9, 10], [11,12]])
print(np.vstack((arr1, arr2)))
print(np.hstack((arr1, arr2)))
The output result is:
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
[[ 1 2 7 8]
[ 3 4 9 10]
[ 5 6 11 12]]
When the sizes of two connected array types are inconsistent
If the code looks like this it will go wrong:
case one
import numpy as np
arr1 = np.array([[1, 2], [3, 4], [5, 6]])
arr2 = np.array([[7, 8], [9, 10], [11]])
print(np.vstack((arr1, arr2)))
print(np.hstack((arr1, arr2)))
# 此种情况输出错误
case two
import numpy as np
arr1 = np.array([[1, 2], [3, 4], [5, 6]])
arr2 = np.array([[7, 8], [9, 10], [11,12,13]])
print(np.vstack((arr1, arr2)))
print(np.hstack((arr1, arr2)))
# 此种情况输出错误
Case three:
import numpy as np
arr1 = np.array([[1, 2], [3, 4], [5, 6]])
arr2 = np.array([[7, 8], [9, 10]])
print(np.vstack((arr1, arr2)))
print(np.hstack((arr1, arr2)))
In this case, there is no problem with the first output, and the correct output result can be obtained. But there is still a problem with the latter output, because there is no principle of ensuring row equality in the subarray.