numpy.concatenate函数用法

numpy.concatenate

这个concatenate用于将矩阵合并,他将沿着已经存在的轴合并一个矩阵,

相关参数有(a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind",

其中第一个参数是用户输入的矩阵, 这些输入的矩阵必须要在将要合并的对应的轴上有相同的形状,

官方文档的机器翻译:矩阵必须具有相同的形状,除非是与轴对应的尺寸(默认为第一个)。

numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")
    Join a sequence of arrays along an existing axis.
    沿着已经存在的轴合并一个矩阵

   相关参数
   Parameters
       a1, a2, …sequence of array_like
       The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
       这些输入的矩阵必须要在将要合并的对应的轴上有相同的形状,

比如,给出两个变量,并将他们沿着axis=1的轴,进行合并:

a = np.arange(3*3).reshape((3,3))
b = np.arange(3*4).reshape((3,4))

a,b
(array([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]]),
 array([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]]))

np.concatenate([a,b],axis=1)
array([[ 0,  1,  2,  0,  1,  2,  3],
       [ 3,  4,  5,  4,  5,  6,  7],
       [ 6,  7,  8,  8,  9, 10, 11]])

上面是沿着列进行合并,尽管他们的列数不同,但是他们的行数相同,因此也可以合并。

 

 axis int, optional
      The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.
      

  如果将axis设置为None,那么将对给出的矩阵先进行展平,即先将其转换为一维数组,再合并,
       默认的axis参数是0:

np.concatenate([a,b],axis=None)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  0,  1,  2,  3,  4,  5,  6,  7,
        8,  9, 10, 11])

 

casting {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional
       Controls what kind of data casting may occur. Defaults to ‘same_kind’.

 

下面给出一些可能触发的错误:

np.concatenate(a,b,axis=None)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-0e550a3d06f6> in <module>
----> 1 np.concatenate(a,b,axis=None)

<__array_function__ internals> in concatenate(*args, **kwargs)

TypeError: concatenate() got multiple values for argument 'axis'

这个类型错误发生的原因是,将要合并的两个数组未添加括号的就作为参数输入了

正确的形式如下:

np.concatenate([a,b],axis=None)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  0,  1,  2,  3,  4,  5,  6,  7,
        8,  9, 10, 11])

或者:

c = (a,b)
np.concatenate(c,axis=None)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  0,  1,  2,  3,  4,  5,  6,  7,
        8,  9, 10, 11])

 

希望这篇文章对你的学习有帮助

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值