我有一行整数,我想作为一列添加到一个二维浮点矩阵。所以当合并时,第一列是int的列,第二列是2D矩阵的第一列,最后一列是矩阵的最后一列
我试着把问题隔离到只有一排,但还是没办法解决。这是最简单的例子
tee = np.array( [[ 0.3322441, -0.34410527, -0.1462533 , 0.35244817, -0.3557416, -0.3362794 ], [ 0.9750831, -0.24571404 , 0.12960567, 0.14683421 ,0.00650549, -0.21060513]] )
zeros = np.array([0])
all_data = np.hstack((zeros, tee))
输出
ValueError Traceback (most recent call last)
<ipython-input-34-02aa17f12182> in <module>()
----> 1 all_data = np.hstack((zeros, tee))
/usr/local/lib/python3.6/dist-packages/numpy/core/shape_base.py in hstack(tup)
336 # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
337 if arrs and arrs[0].ndim == 1:
--> 338 return _nx.concatenate(arrs, 0)
339 else:
340 return _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions
期望输出
print(all_data)
[[0],[ 0.3322441, -0.34410527, -0.1462533 , 0.35244817, -0.3557416, -0.3362794 ], [ 0.9750831, -0.24571404 , 0.12960567, 0.14683421 ,0.00650549, -0.21060513]]
在NumPy数组中混合数据类型的唯一方法是使用数据类型:
np.object
。这可以这样做:或者明确地说:
您可以使用
np.column_stack
:这将产生以下输出:
方法不起作用的原因是,试图将一个元素的列前置到纵轴长度为2的二维数组中。但是,上面的方法将整数转换为浮点。如果这是不需要的,您可能需要查看列表列表,列表可以创建为:
从而产生输出:
相关问题 更多 >
编程相关推荐