所以我有一个 numpy 数组,其中包含:
arr = [1 2 3 4 5 6]
当我执行时:
print(arr.shape)
它给了我:
(6,)
我正在尝试添加常量值 3
const_val = 3
进入数组的维度,这样我就可以获得:
(6,3)
首先,我尝试通过以下方式扩展数组的维度:
arr = np.expand_dims(arr, axis = -1)
现在在哪里:
print(arr.shape)
返回我:
(6,1)
但是,当我尝试 reshape 数组维度以将 1 替换为常量值 3 时,
arr = np.reshape(arr, (arr.shape[0], const_val))
我收到错误消息:
ValueError: cannot reshape array of size 6 into shape (6,3)
我可以知道为什么会发生这种情况吗?
最佳答案
您想向数组添加两个空列吗?在这种情况下,您可以连接大小为 (6,2) 的矩阵:
arr = np.array([1,2,3,4,5,6]).reshape(6,1)
to_add = np.zeros((6,2))
res = np.concatenate((arr, to_add), axis=1)
关于python - 扩展 numpy 数组维度并 reshape ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56111551/