变形、拼接#
import numpy as np
reshape 函数#
x = np.arange(12)
x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
# 3行4列的数组
x.reshape(3, 4)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
# 用-1来自动计算最后一维
x.reshape(2, 3, -1)
array([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]])
# 改变数组形状
x = x.reshape(-1, 2)
x
array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11]])
# flatten 等价于 reshape(-1)
x.flatten(), x.reshape(-1)
(array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]),
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))
数组拼接#
x = np.arange(6).reshape(2, 3)
y = np.ones((2, 3))
x, y
(array([[0, 1, 2],
[3, 4, 5]]),
array([[1., 1., 1.],
[1., 1., 1.]]))
# 垂直向拼接
np.concatenate((x, y))
array([[0., 1., 2.],
[3., 4., 5.],
[1., 1., 1.],
[1., 1., 1.]])
# 水平向拼接
np.concatenate((x, y), axis=1)
array([[0., 1., 2., 1., 1., 1.],
[3., 4., 5., 1., 1., 1.]])
# 垂直向拼接
np.vstack((x, y))
array([[0., 1., 2.],
[3., 4., 5.],
[1., 1., 1.],
[1., 1., 1.]])
# 水平向拼接
np.hstack((x, y))
array([[0., 1., 2., 1., 1., 1.],
[3., 4., 5., 1., 1., 1.]])