Numpy:矩阵拼接

矩阵拼接方法:
  • np.append(arr,values,axis)
  • np.concatenate(arrays,axis,out=None)
  • np.stack(arrays,axis,out=None)
  • np.hstack/vstack(tup)

下面具体举例,注意输入和输出维度的关系。

1. 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)
2. 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)
3. 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)
4. 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()完成绝大部分功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值