numpy.concatenate
语法
numpy.concatenate((a1,a2,...), axis=0, out=None, dtype=None, casting="same_kind")
作用
将一个数组序列在指定的维度上进行连接join
Parameter
- a1,a2,… : sequence of array_like
The arrays must have the same shape, except in the dimension corresponding to
axis
(the first, by default)
数组序列的shape
在除了axis
指定维度以外的所有维度上都应该相同。axis默认为第一个维度,即axis=0
。
- axis : int, optional
The axis along which the arrays will be joined. If axis is None, arraysare flattened before use. Default is 0.
axis
指定了数组进行join操作的维度。默认为0,即第一维。如果axis=None
,那么数组将会先展平,再进行join。
- out : ndarray, optional
If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.
如果指定了out
,则将join后的结果输出到out
指定的数组中,但shape
必须正确。如果没有指定out
,则会返回一个匹配大小的数组。
- dtype : str or dtype,optional
If provided, the destination array will have this dtype. Cannot be provided together with
out
.
如果提供了dtype
,则输出的数组的数据类型会与dtype
中指定的一致。不可以同时与out
一起指定。1.20.0中新增,以前的numpy无法使用。
- casting : { ‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’ }, optional
Controls what kind of data casting may occur.Defaults to ‘same_kind’.
‘no’
means the data types should not be cast at all.‘equiv’
means only byte-order changes are allowed.‘safe’
means only casts which can preserve values are allowed.‘same_kind’
means only safe casts or casts within a kind, like float64 to float32, are allowed.‘unsafe’
means any data conversions may be done.
控制数据类型的cast
,共有五种类型。不表。1.20.0中新增,以前的numpy无法使用。
Example
>>> a = np.array([[[1,2,3,4],[4,5,6,7]],[[2,3,4,5],[5,6,7,8]],[[3,4,5,6],[4,5,6,7]]])
>>> print(a.shape)
>>> b = np.array([[[1,2,3,4],[4,5,6,7]],[[2,3,4,5],[5,6,7,8]]])
>>> print(b.shape)
>>> x = np.concatenate((a,b),axis = 0)
>>> print(x.shape)
结果如图:
可见,在指定维度上,第0维进行了join。
>>> x1 = np.concatenate((a,b),axis = 1)
结果如图:
可以看出,如果指定axis=1
,则会报错,因为除了axis=1
的其他维度上,shape并不相等。
>>> x2 = np.concatenate((a,b),axis=None)
>>> print(x2.shape)
可以看出,数组被展平了。
注意事项
When one or more of the arrays to be concatenated is a
MaskedArray
, this function will return aMaskedArray
object instead of anndarray
, but theinput masks
are not preserved. In cases where aMaskedArray
is expected as input, use thema.concatenate
function from the masked array module instead.
当有一个或者多个MaskedArray
作为输入进行concatenate
时,不再会返回一个ndarray
,而是会返回MaskedArray
,但是其mask
不会保留,所以在输入中有MaskedArray
的情况下,应该尽量使用ma.concatenate
,而不是np.concatenate()
。
如果觉得文章对您有帮助的话,可以点个赞,是对博主最大的肯定!