You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行x_mat = np.hstack((mat_head, mat_body))维度不匹配报错如何解决?

问题原因

np.hstack() 执行水平拼接时要求所有输入数组的维度数完全一致,本次报错的核心原因是两个输入数组维度不匹配:

  • 索引0的mat_head为1维数组
  • 索引1的mat_body为2维数组
解决方法

根据你需要的拼接效果选择对应方案即可:

方案1:手动调整维度后用np.hstack拼接

如果需要把1维的mat_head作为新列拼到mat_body的左侧,先给mat_head增加一个维度,让它转为2维数组:

# 给1维数组增加列维度,shape从(N,)转为(N,1)
mat_head_2d = mat_head[:, np.newaxis]
# 等效写法:mat_head_2d = mat_head.reshape(-1, 1)
x_mat = np.hstack((mat_head_2d, mat_body))

如果需要把mat_head作为新行拼到mat_body的上方/下方,推荐改用np.vstack做垂直拼接,同时给mat_head增加行维度:

# 给1维数组增加行维度,shape从(M,)转为(1,M)
mat_head_2d = mat_head[np.newaxis, :]
# 等效写法:mat_head_2d = mat_head.reshape(1, -1)
x_mat = np.vstack((mat_head_2d, mat_body))

方案2:使用专用拼接函数自动处理维度

如果是做列方向拼接,直接用np.column_stack即可,它会自动将1维数组转为2维列向量,无需手动调整维度:

x_mat = np.column_stack((mat_head, mat_body))

如果是做行方向拼接,直接用np.row_stack即可,自动将1维数组转为2维行向量:

x_mat = np.row_stack((mat_head, mat_body))

内容的提问来源于stack exchange,提问作者Deepshikha Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:54:02