沿第二个轴连接两个一维 `numpy` 数组

25

执行中

import numpy as np
t1 = np.arange(1,10)
t2 = np.arange(11,20)

t3 = np.concatenate((t1,t2),axis=1)

导致结果为

Traceback (most recent call last):

  File "<ipython-input-264-85078aa26398>", line 1, in <module>
    t3 = np.concatenate((t1,t2),axis=1)

IndexError: axis 1 out of bounds [0, 1)

为什么会报告轴1超出范围?

5个回答

20

您的标题已经解释了这一点-一维数组没有第二个轴!

但是话虽如此,在我的系统上和@Oliver W.的系统上一样,它不会产生错误。

In [655]: np.concatenate((t1,t2),axis=1)
Out[655]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 11, 12, 13, 14, 15, 16, 17, 18,
       19])

这是我期望从axis=0得到的结果:

In [656]: np.concatenate((t1,t2),axis=0)
Out[656]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 11, 12, 13, 14, 15, 16, 17, 18,
       19])

看起来在数组为1d时,concatenate忽略了axis参数。我不知道这是我的1.9版本中的新问题,还是旧问题。

如果需要更多控制,请考虑使用vstackhstack包装器,它们会根据需要扩展数组维度:

In [657]: np.hstack((t1,t2))
Out[657]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 11, 12, 13, 14, 15, 16, 17, 18,
       19])

In [658]: np.vstack((t1,t2))
Out[658]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9],
       [11, 12, 13, 14, 15, 16, 17, 18, 19]])

16
这是因为Numpy表示一维数组的方式。使用reshape()方法可以解决此问题:
t3 = np.concatenate((t1.reshape(-1,1),t2.reshape(-1,1),axis=1)

解释: 这是初始创建时1D数组的形状:

t1 = np.arange(1,10)
t1.shape
>>(9,)

'np.concatenate'和许多其他函数不喜欢缺失的维度。Reshape执行以下操作:

t1.reshape(-1,1).shape
>>(9,1) 

10
如果你需要一个有两列的数组,你可以使用column_stack函数:
import numpy as np
t1 = np.arange(1,10)
t2 = np.arange(11,20)
np.column_stack((t1,t2))

哪些结果

[[ 1 11]
 [ 2 12]
 [ 3 13]
 [ 4 14]
 [ 5 15]
 [ 6 16]
 [ 7 17]
 [ 8 18]
 [ 9 19]]

5
你最好使用Numpy的另一个函数numpy.stack。它的行为类似于MATLAB的catnumpy.stack函数不要求数组在连接维度上具有相同的形状。

0
这是因为你需要将它转换成两个维度,因为一个维度无法连接。通过这样做,您可以添加一个空列。如果您运行以下代码,它就会起作用:
import numpy as np 
t1 = np.arange(1,10)[None,:]
t2 = np.arange(11,20)[None,:]
t3 = np.concatenate((t1,t2),axis=1)
print(t3)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接