转:https://blog.csdn.net/qq_42191914/article/details/108683992
矩阵拼接方法:
np.append(arr,values,axis)
np.concatenate(arrays,axis,out=None)
np.stack(arrays,axis,out=None)
np.hstack/vstack(tup)
下面具体举例,注意输入和输出维度的关系。
- np.append(arr,values,axis)
支持数组和数组或数组和数的拼接,不支持三个及以上数组的拼接,axis默认值为None
两个(3,4)维度的数组
a = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
])
b = np.array([
['a','b','c','d'],
['e','f','g','h'],
['i','j','k','l']
])
c = np.append(a,b) # 默认axis=None
d = np.append(a,b,axis=0)
e = np.append(a,b,axis=1) # 等效于axis=-1
print(c, c.shape)
print(d, d.shape)
print(e, e.shape)
[out]:
['1' '2' '3' '4' '5' '6' '7' '8' '9' '10' '11' '12' 'a' 'b' 'c' 'd' 'e'
'f' 'g' 'h' 'i' 'j' 'k' 'l'] (24,)
[['1' '2' '3' '4']
['5' '6' '7' '8']
['9' '10' '11' '12']
['a' 'b' 'c' 'd']
['e' 'f' 'g' 'h']
['i' 'j' 'k' 'l']] (6, 4)
[['1' '2' '3' '4' 'a' 'b' 'c' 'd']
['5' '6' '7' '8' 'e' 'f' 'g' 'h']
['9' '10' '11' '12' 'i' 'j' 'k' 'l']] (3, 8)
- np.concatenate(arrays,axis,out=None)
功能与np.append()类似,但是支持多个数组的拼接,axis默认值为0
c = np.concatenate((a,b),axis=None)
d = np.concatenate((a,b)) # 默认axis=0
e = np.concatenate((a,b),axis=1)
print(c, c.shape)
print(d, d.shape)
print(e, e.shape)
[out]:
['1' '2' '3' '4' '5' '6' '7' '8' '9' '10' '11' '12' 'a' 'b' 'c' 'd' 'e'
'f' 'g' 'h' 'i' 'j' 'k' 'l'] (24,)
[['1' '2' '3' '4']
['5' '6' '7' '8']
['9' '10' '11' '12']
['a' 'b' 'c' 'd']
['e' 'f' 'g' 'h']
['i' 'j' 'k' 'l']] (6, 4)
[['1' '2' '3' '4' 'a' 'b' 'c' 'd']
['5' '6' '7' '8' 'e' 'f' 'g' 'h']
['9' '10' '11' '12' 'i' 'j' 'k' 'l']] (3, 8)
- np.stack(arrays,axis,out=None)
同样支持多矩阵拼接,不同的是,stack会添加一个新的维度,axis默认值为0
c = np.stack((a,b)) # 默认axis=0
d = np.stack((a,b), axis=1)
e = np.stack((a,b), axis=2)
print(c, c.shape)
print(d, d.shape)
print(e, e.shape)
[out]:
[[['1' '2' '3' '4']
['5' '6' '7' '8']
['9' '10' '11' '12']]
[['a' 'b' 'c' 'd']
['e' 'f' 'g' 'h']
['i' 'j' 'k' 'l']]] (2, 3, 4)
[[['1' '2' '3' '4']
['a' 'b' 'c' 'd']]
[['5' '6' '7' '8']
['e' 'f' 'g' 'h']]
[['9' '10' '11' '12']
['i' 'j' 'k' 'l']]] (3, 2, 4)
[[['1' 'a']
['2' 'b']
['3' 'c']
['4' 'd']]
[['5' 'e']
['6' 'f']
['7' 'g']
['8' 'h']]
[['9' 'i']
['10' 'j']
['11' 'k']
['12' 'l']]] (3, 4, 2)
- np.hstack(tup)/np.vstack(tup)
水平/垂直堆叠,对多维数组来说,水平堆叠相当于在第二个维度做concatenation,垂直堆叠相当于在第一个维度做concatenation
c = np.hstack((a,b))
d = np.vstack((a,b))
print(c, c.shape)
print(d, d.shape)
[out]:
[['1' '2' '3' '4' 'a' 'b' 'c' 'd']
['5' '6' '7' '8' 'e' 'f' 'g' 'h']
['9' '10' '11' '12' 'i' 'j' 'k' 'l']] (3, 8)
[['1' '2' '3' '4']
['5' '6' '7' '8']
['9' '10' '11' '12']
['a' 'b' 'c' 'd']
['e' 'f' 'g' 'h']
['i' 'j' 'k' 'l']] (6, 4)
总结:np.stack()会扩充维度,不扩充维度的话可以使用np.concatenate()完成绝大部分功能。