python - 如何仅 reshape numpy中的最后一个维度?

标签 python numpy multidimensional-array reshape

假设我有 A形状(...,96)想把它改造成(...,32,3)保持前面维度的长度和数量(如果有的话)完整无缺。

这该怎么做?

如果我写

np.reshape(A, (-1, 32, 2))

它会将所有先前的维度展平为一个我不想要的单一维度。

最佳答案

一种方法是使用与新分割轴长度连接的形状信息计算新的形状元组,然后重新整形 -

A.reshape(A.shape[:-1] + (32,3))

sample 运行 -
In [898]: A = np.random.rand(5,96)

In [899]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[899]: (5, 32, 3)

In [900]: A = np.random.rand(10,11,5,96)

In [901]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[901]: (10, 11, 5, 32, 3)

甚至适用于 1D大批 -
In [902]: A = np.random.rand(96)

In [903]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[903]: (32, 3)

工作是因为串联的引导轴是空的,因此只在那里使用分割轴长度 -
In [904]: A.shape[:-1]
Out[904]: ()

In [905]: A.shape[:-1] + (32,3)
Out[905]: (32, 3)

关于python - 如何仅 reshape numpy中的最后一个维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183967/

相关文章:

python - 企业社会责任矩阵构建缓慢

python - 相似代码之间 numpy 的巨大速度差异

python - 如何从字符串中删除所有标点符号?

python - 将列替换为特定字符的计数

python - numpy:使用运算符 - 数组包含 None

c - 指向二维数组的指针

Java计算数组中字符的大小

java - 3维数组索引越界

python - 您如何通过其 API 将差异发布到 ReviewBoard?

python - Vertica从本地文件复制,处理连接重置