执行
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超出范围?
你的标题解释了它 - 一个1d阵列没有第二轴!
但话说回来,就像我在Qazxswpois上的系统一样,它不会产生错误
@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
当数组为1d时,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])
看起来忽略了concatenate
参数。我不知道这是我的1.9版本中的新内容,还是旧版本。
要获得更多控制,请考虑使用axis
和vstack
包装器,如果需要,可以扩展数组维度:
hstack
这是因为Numpy表示一维数组的方式。以下使用reshape()将起作用:
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]])
说明:这是最初创建时的1D数组的形状:
t3 = np.concatenate((t1.reshape(-1,1),t2.reshape(-1,1),axis=1)
'np.concatenate'和许多其他函数不喜欢缺少的维度。重塑执行以下操作:
t1 = np.arange(1,10)
t1.shape
>>(9,)
你最好使用名为t1.reshape(-1,1).shape
>>(9,1)
的Numpy的不同功能。
它的行为类似于MATLAB的numpy.stack
。
cat
函数不要求数组具有它们连接在一起的维度。
这是因为您需要将其更改为二维,因为一个维度无法连接。通过执行此操作,您可以添加一个空列。如果您运行以下代码,它可以工作:
numpy.stack
如果需要包含两列的数组,可以使用column_stack:
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)
哪个结果
import numpy as np
t1 = np.arange(1,10)
t2 = np.arange(11,20)
np.column_stack((t1,t2))