python - numpy concatenate 不将新数组附加到空多维数组

标签 python arrays numpy multidimensional-array concatenation

我敢打赌我正在做一些非常简单的错误。我想从一个空的 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/

相关文章:

c - 'C' 使用 strstr() 并减去两个指针从大缓冲区中获取子字符串的长度

ruby - 在 Ruby 中扫描字符串数组以查找匹配项

python - 只有 size-1 数组可以转换为 Python 标量

python - Numpy:快速设置数组元素

python - 使用 pymnet 固定多路网络图中节点的位置

python 情节9: color brewer not enough

python - 无法将 Base64 字符串转换为图像

python - Python 高手如何识别和检查 Python 3 数据结构的内容?

php - 在 PHP 中更新多维数组

python - 值错误: Found input variables with inconsistent numbers of samples: [100, 300]