来源:https://blog.csdn.net/bqw18744018044/article/details/81160600
函数名 | 功能 |
---|---|
concatenate | 连接多个数组 |
vstack | 沿第0轴连接数组 |
hstack | 沿第1轴连接数组 |
column_stack | 按列连接多个一维数组 |
split、array_split | 将数组分为多段 |
transpose | 重新设置轴的顺序 |
swapaxes | 交换两个轴的顺序 |
一、连接数组
1
2
3
4
5
6
7
8
import numpy as np
a = np.arange(3)
b = np.arange(10,13)
print(a)
print(b)
[0 1 2]
[10 11 12]
1.最基本的函数:concatenate
1
2
3
np.concatenate((a,b)) # 默认axis=0
array([ 0, 1, 2, 10, 11, 12])
2.vstack:垂直连接数组(axis=0)
1
2
3
4
np.vstack((a,b))
array([[ 0, 1, 2],
[10, 11, 12]])
3.hstack:水平连接数组(axis=1)
1
2
3
np.hstack((a,b))
array([ 0, 1, 2, 10, 11, 12])
4.c_[]对象:将向量按列合并
1
2
3
4
5
np.c_[a,b,a+b]
array([[ 0, 10, 10],
[ 1, 11, 12],
[ 2, 12, 14]])
二、拆分数组
1.split:严格平均划分
1
2
3
4
5
6
7
8
9
10
np.random.seed(42)
a = np.random.randint(0,10,12)
np.split(a,6) # 将数组a划分成相等的6份
[array([6, 3]),
array([7, 4]),
array([6, 9]),
array([2, 6]),
array([7, 4]),
array([3, 7])]
2.array_split:尽量平均划分
1
2
3
4
5
6
7
np.array_split(a,5)
[array([6, 3, 7]),
array([4, 6, 9]),
array([2, 6]),
array([7, 4]),
array([3, 7])]
三、调整轴顺序
1.transpose:重新指定轴顺序
1
2
3
4
5
6
a = np.random.randint(0,10,(2,3,4,5))
print("原数组形状:",a.shape)
print("transpose:",np.transpose(a,(1,2,0,3)).shape)#重新指定轴0到3的顺序
原数组形状: (2, 3, 4, 5)
transpose: (3, 4, 2, 5)
2.swapaxes:交换两个轴
1
2
print("swapaxes:",np.swapaxes(a,1,2).shape)#交换轴1和2
swapaxes: (2, 4, 3, 5)