python - 扩展 numpy 数组维度并 reshape

标签 python arrays numpy

所以我有一个 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/

相关文章:

python - Pandas:循环每一行,提取特征并创建新列

python - SciPy插值: precision of methods?

javascript - 如何从 javascript 运行 python 脚本?

python - 排除具有空单元格的行

python - 从 href 和文本中获取 url

C - 使用 strtok 只给我每行的第一个单词?

javascript - 从对象数组中删除 JSON 对象

PHP - 提取关联 POST 数据的最佳方式

python - 如何生成包含 3-sigma 异常值的随机数数组?

python - 基本类型 (int) 和复杂类型 (np.ndarray) 之间的行为差​​异