numpy数组连接:"ValueError:所有输入数组必须具有相同的维数"

Rad*_*duS 20 python numpy

如何连接这些numpy数组?

首先np.array是一个形状(5,4)

[[  6487    400 489580      0]
 [  6488    401 492994      0]
 [  6491    408 489247      0]
 [  6491    408 489247      0]
 [  6492    402 499013      0]]
Run Code Online (Sandbox Code Playgroud)

第二个np.array有形状(1,5)

[  16.   15.   12.  12.  17. ]
Run Code Online (Sandbox Code Playgroud)

最后的结果应该是

[[  6487    400    489580    0   16]
 [  6488    401    492994    0   15]
 [  6491    408    489247    0   12]
 [  6491    408    489247    0   12]
 [  6492    402    499013    0   17]]
Run Code Online (Sandbox Code Playgroud)

我试过np.concatenate([array1, array2]) 但是我得到了这个错误

ValueError: all the input arrays must have same number of dimensions

我究竟做错了什么?

Div*_*kar 25

要使用np.concatenate,我们需要扩展第二个数组2D,然后连接axis=1-

np.concatenate((a,b[:,None]),axis=1)
Run Code Online (Sandbox Code Playgroud)

或者,我们可以使用np.column_stack它照顾它 -

np.column_stack((a,b))
Run Code Online (Sandbox Code Playgroud)

样品运行 -

In [84]: a
Out[84]: 
array([[54, 30, 55, 12],
       [64, 94, 50, 72],
       [67, 31, 56, 43],
       [26, 58, 35, 14],
       [97, 76, 84, 52]])

In [85]: b
Out[85]: array([56, 70, 43, 19, 16])

In [86]: np.concatenate((a,b[:,None]),axis=1)
Out[86]: 
array([[54, 30, 55, 12, 56],
       [64, 94, 50, 72, 70],
       [67, 31, 56, 43, 43],
       [26, 58, 35, 14, 19],
       [97, 76, 84, 52, 16]])
Run Code Online (Sandbox Code Playgroud)

如果b它是一个形状的1D数组,很可能所有数据都包含在其中的唯一元素中,我们需要在连接之前将其展平.为此,我们也可以使用它.这是一个示例运行,以明确 - dtype=object(1,)np.concatenate

In [118]: a
Out[118]: 
array([[54, 30, 55, 12],
       [64, 94, 50, 72],
       [67, 31, 56, 43],
       [26, 58, 35, 14],
       [97, 76, 84, 52]])

In [119]: b
Out[119]: array([array([30, 41, 76, 13, 69])], dtype=object)

In [120]: b.shape
Out[120]: (1,)

In [121]: np.concatenate((a,np.concatenate(b)[:,None]),axis=1)
Out[121]: 
array([[54, 30, 55, 12, 30],
       [64, 94, 50, 72, 41],
       [67, 31, 56, 43, 76],
       [26, 58, 35, 14, 13],
       [97, 76, 84, 52, 69]])
Run Code Online (Sandbox Code Playgroud)

  • b[:, None] 表示法很棒,但也值得一提 b.reshape() (2认同)