python中np.concatenate 的 axis=1 和axis=-1 有啥区别

源代码中给的例子:

​
 Examples
    --------
    >>> a = np.array([[1, 2], [3, 4]])
    >>> b = np.array([[5, 6]])
    >>> np.concatenate((a, b), axis=0)
    array([[1, 2],
           [3, 4],
           [5, 6]])

    """
        a=> (2,2)
        b=> (1,2) 
        如果是第二维要拼接,其他维度需要同一样的维度,所以b需要转置。b=> (2,1)
    """
    >>> np.concatenate((a, b.T), axis=1) #所以b需要转置。b=> (2,1)
    array([[1, 2, 5],
           [3, 4, 6]])
    >>> np.concatenate((a, b), axis=None)
    array([1, 2, 3, 4, 5, 6])

​

axis=0:在第一维拼接:其他维度的需要是相同的维度;

axis=1:在第二维拼接:其他维度的需要是相同的维度;

axis=-1:最后一维拼接:其他维度的需要是相同的维度;

import numpy as np
"""
a=> a的维度:(3, 2, 2)
b=> b的维度:(3, 2, 2)
"""
a=np.array([
    [[1,2],[3,4]],
    [[5,6],[7,8]],
    [[8,9],[8,9]]
])
b=np.array([
    [[1,2],[2,3]],
    [[4,5],[4,5]],
    [[5,6],[6,7]]
])
print(a.shape)
print(b.shape)
print("=================================")
res1=np.concatenate((a,b),axis=0)
print(res1.shape)
print(res1)
print("=================================")
res2=np.concatenate((a,b),axis=1)
print(res2.shape)
print(res2)
print("=================================")
res3=np.concatenate((a,b),axis=-1)
print(res3.shape)
print(res3)
=================================
(6, 2, 2) axis=0
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]

 [[8 9]
  [8 9]]

 [[1 2]
  [2 3]]

 [[4 5]
  [4 5]]

 [[5 6]
  [6 7]]]
=================================
(3, 4, 2) axis=1
[[[1 2]
  [3 4]
  [1 2]
  [2 3]]

 [[5 6]
  [7 8]
  [4 5]
  [4 5]]

 [[8 9]
  [8 9]
  [5 6]
  [6 7]]]
=================================
(3, 2, 4) axis=-1
[[[1 2 1 2]
  [3 4 2 3]]

 [[5 6 4 5]
  [7 8 4 5]]

 [[8 9 5 6]
  [8 9 6 7]]]

注意:如果需要拼接某一维度,那其维度的维数要相同。当a,b是二维数组时,axis=1 和axis=-1操作的都是最后一维。

a = np.array([[1, 2], [3, 4]])  #(2,2)
b = np.array([[5, 6]])  #(1,2)

res4=np.concatenate((a,b),axis=0)
print("res4:",res4.shape)

res5=np.concatenate((a,b.T),axis=1)
print("res5:",res5.shape)

********************************

res4: (3, 2) ==>(2+1=3, 2)
res5: (2, 3) ===>(2,2+1=3)
res6: (2, 3) ===>(2,2+1=3)

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值