日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

numpy.concatenate函數用法詳解_python

作者:houyushui ? 更新時間: 2023-05-07 編程語言

這個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])

原文鏈接:https://blog.csdn.net/houyushui/article/details/116894753

欄目分類
最近更新