我敢打赌我正在做一些非常简单的错误。我想从一个空的 2D numpy 数组开始,并向其附加数组(尺寸为 1 行 x 4 列)。
open_cost_mat_train = np.matrix([])
for i in xrange(10):
open_cost_mat = np.array([i,0,0,0])
open_cost_mat_train = np.vstack([open_cost_mat_train,open_cost_mat])
我的错误跟踪是:
File "/Users/me/anaconda/lib/python2.7/site-packages/numpy/core/shape_base.py", line 230, in vstack
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
我做错了什么?我尝试过追加、连接、将空的二维数组定义为 [[]]
、[]
、array([])
等等其他。
最佳答案
您需要 reshape 原始矩阵,以便列数与附加数组匹配:
open_cost_mat_train = np.matrix([]).reshape((0,4))
之后,它给出:
open_cost_mat_train
# matrix([[ 0., 0., 0., 0.],
# [ 1., 0., 0., 0.],
# [ 2., 0., 0., 0.],
# [ 3., 0., 0., 0.],
# [ 4., 0., 0., 0.],
# [ 5., 0., 0., 0.],
# [ 6., 0., 0., 0.],
# [ 7., 0., 0., 0.],
# [ 8., 0., 0., 0.],
# [ 9., 0., 0., 0.]])
关于python - numpy concatenate 不将新数组附加到空多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596674/