import numpy as np
# 数组的合并操作
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
np.concatenate([x, y])
# 结果:[1, 2, 3, 4, 5, 6]
A = np.array([[1, 2, 3],
[4, 5, 6]])
np.concatenate([A, A])
# 结果:
# [[1 2 3]
# [4 5 6]
# [1 2 3]
# [4 5 6]]
# 沿着列方向进行拼接 axis:轴
np.concatenate([A, A], axis=1)
# 结果:
# [[1 2 3 1 2 3]
# [4 5 6 4 5 6]]
# np.concatenate方法不支持不同的维度,只能维度相同,若要拼接请转换成相同维度
z = np.array([666, 666, 666])
A = np.array([[1, 2, 3],
[4, 5, 6]])
np.concatenate([A, z.reshape(1, -1)])
# 结果:
# [[ 1 2 3]
# [ 4 5 6]
# [666 666 666]]
# 比concatenate函数更好的垂直拼接方法:vstack
z = np.array([666, 666, 666])
A = np.array([[1, 2, 3],
[4, 5, 6]])
np.vstack([A, z])
# 结果:
# [[ 1 2 3]
# [ 4 5 6]
# [666 666 666]]
# vstack函数的运用
A = np.array([[1, 2, 3],
[4, 5, 6]])
B = np.full((2, 2), 100)
np.hstack([A, B])
# 结果:
# [[ 1 2 3 100 100]
# [ 4 5 6 100 100]]
# 分割操作np.split
# 一维:
x = np.arange(10)
x1, x2, x3 = np.split(x, [3, 7]) # 分割成三段
# print(x1) :[0 1 2]
# print(x2) :[3 4 5 6]
# print(x3) :[7 8 9]
# 二维:
A = np.arange(16).reshape((4, 4))
# print(A) :[[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]
A1, A2 = np.split(A, [2])
# print(A1) :[[0 1 2 3]
# [4 5 6 7]]
# print(A2):[[ 8 9 10 11]
# [12 13 14 15]]
A1, A2 = np.split(A, [2], axis=1) # 列分割
# print(A1) :[[ 0 1]
# [ 4 5]
# [ 8 9]
# [12 13]]
# print(A2) :[[ 2 3]
# [ 6 7]
# [10 11]
# [14 15]]
# 更好的分割函数vsplit、hsplit
A = np.arange(16).reshape((4, 4))
upper, lower = np.vsplit(A, [2])
# print(upper) :[[0 1 2 3]
# [4 5 6 7]]
# print(lower):[[ 8 9 10 11]
# [12 13 14 15]]
left, right = np.hsplit(A, [2])
# print(left) :[[ 0 1]
# [ 4 5]
# [ 8 9]
# [12 13]]
# print(right) :[[ 2 3]
# [ 6 7]
# [10 11]
# [14 15]]
X, y = np.hsplit(A, [-1])
# print(X) :[[ 0 1 2]
# [ 4 5 6]
# [ 8 9 10]
# [12 13 14]]
# print(y ):[[ 3]
# [ 7]
# [11]
# [15]]
# 将y变换成向量:行全部抽出
newY = y[:, 0]
# print(newY)
# [ 3 7 11 15]