numpy.concatenate函数用法详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

numpy.concatenate函数用法详解

houyushui   2023-03-20 我要评论

这个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])

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们