简体   繁体   English

尝试连接两个不同维度的数组

[英]Trying to join two arrays with different dimensions

I'm learning python and I have 2 arrays:我正在学习 python,我有 2 个数组:

a = [[ 1 , 2 ]
      [3,  4]]
b = [ 6,7]

when I print the shapes I get:当我打印形状时,我得到:

a.shape = (2,2)
b.shape = (2,)

want result to be:希望结果是:

c = [[ 1, 2 , 6]
     [3, 4, 7]]

I've tried我试过了

c = a + b

and

c = np.concatenate((a, b),axis=None) #tried axis=0, axis=1

I keep getting errors like我不断收到错误,例如

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

May be you can try as shown in numpy example but b needs to be of shape (1, 2) by just adding array as a inner element of array: np.array([[6,7]])可能你可以像numpy 示例中所示那样尝试,但b需要形状为(1, 2) ,只需将数组添加为数组的内部元素: np.array([[6,7]])

a = np.array([[1, 2 ],
              [3, 4]])
b = np.array([[6,7]])

c = np.concatenate((a, b.T), axis=1)

Output:输出:

[[1 2 6]
 [3 4 7]]

You can use numpy.vstack您可以使用numpy.vstack

In [22]: import numpy as np

In [23]: a = np.array([[1,2], [3,4]])

In [24]: b = np.array([6,7])

In [25]: np.vstack((a.T, b)).T
Out[25]:
array([[1, 2, 6],
       [3, 4, 7]])
In [868]: a = np.array([[1,2],[3,4]]); b = np.array([6,7])
In [869]: a.shape, b.shape
Out[869]: ((2, 2), (2,))

b has 1 dimension, it needs 2 to match a : b有 1 维,它需要 2 来匹配a

In [870]: np.reshape(b,(2,1))
Out[870]: 
array([[6],
       [7]])

Now concatenate works:现在concatenate工作:

In [871]: np.concatenate((a, np.reshape(b,(2,1))), axis=1)
Out[871]: 
array([[1, 2, 6],
       [3, 4, 7]])

np.vstack works because it adds a new initial dimension if needed. np.vstack起作用,是因为它在需要时添加了一个新的初始维度。 I added a trailing dimension.我添加了一个尾随维度。

In the long run to use concatenate effectively you must learn about dimensions, and how to adjust them if needed.从长远来看,要有效地使用concatenate您必须了解维度,以及如何在需要时调整它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM