In [14]: A=np.array([[1.,2,3],[4,5,6],[7,8,9],[10,11,12]])
...: print(A)
...: x,y=A.shape
...: B=np.full(x,-1.0)
...: print(B)
[[ 1. 2. 3.]
[ 4. 5. 6.]
[ 7. 8. 9.]
[10. 11. 12.]]
[-1. -1. -1. -1.]
In [15]: A.shape
Out[15]: (4, 3)
In [16]: B.shape
Out[16]: (4,)
您的尺寸错误:
In [17]: np.concatenate((A,B), 1)
Traceback (most recent call last):
File "<ipython-input-17-8dc80544006c>", line 1, in <module>
np.concatenate((A,B), 1)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)
问题应该很明显。一个数组是 (4,3),另一个是 (4,),2d 和 1d。
我们可以轻松地向B 添加维度(B.reshape(4,1) 也可以):
In [18]: B[:,None].shape
Out[18]: (4, 1)
In [19]: np.concatenate((A,B[:,None]), 1)
Out[19]:
array([[ 1., 2., 3., -1.],
[ 4., 5., 6., -1.],
[ 7., 8., 9., -1.],
[10., 11., 12., -1.]])
尝试其他功能没有帮助。从 hstack 错误中可以明显看出,它只是将作业传递给 concatenate:
In [20]: np.hstack((A,B))
Traceback (most recent call last):
File "<ipython-input-20-56593299da4e>", line 1, in <module>
np.hstack((A,B))
File "<__array_function__ internals>", line 5, in hstack
File "/usr/local/lib/python3.8/dist-packages/numpy/core/shape_base.py", line 346, in hstack
return _nx.concatenate(arrs, 1)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)
np.append 也可以。
column_stack 也使用concatenate,但将数组调整为二维:
In [22]: np.column_stack((A,B))
Out[22]:
array([[ 1., 2., 3., -1.],
[ 4., 5., 6., -1.],
[ 7., 8., 9., -1.],
[10., 11., 12., -1.]])
注意错误信息,并尝试从中学习。你未来的编程自我会感谢你!