【问题标题】:Adding dimension to ndarray and reshaping向 ndarray 添加维度并重塑
【发布时间】:2026-01-30 05:50:01
【问题描述】:

我有一个形状为 (16,2) 的 numpy 数组

[[-109.12722222    1454.        ]
 [-109.12694444    1459.        ]
 [-109.12666667    1463.        ]
 [-109.12638889    1465.        ]
 [-109.12611111    1464.        ]
 [-109.12583333    1464.        ]
 [-109.12555556    1464.        ]
 [-109.12527778    1464.        ]
 [-109.125         1464.        ]
 [-109.12472222    1465.        ]
 [-109.12444444    1465.        ]
 [-109.12416667    1463.        ]
 [-109.12388889    1462.        ]
 [-109.12361111    1461.        ]
 [-109.12333333    1459.        ]
 [-109.12305556    1454.        ]]

我想知道如何将它重塑为 (4,4,2)。

[[-109.12722222    1454.        ] [-109.12694444    1459.        ][-109.12666667    1463.        ][-109.12638889    1465.        ]
 [-109.12611111    1464.        ] [-109.12583333    1464.        ] [-109.12555556    1464.        ][-109.12527778    1464.        ]
 [-109.125         1464.        ][-109.12472222    1465.        ][-109.12444444    1465.        ][-109.12416667    1463.        ]
 [-109.12388889    1462.        ][-109.12361111    1461.        ][-109.12333333    1459.        ][-109.12305556    1454.        ]]

我试过这个:

numpy_array = np.reshape(4, 4, 2)

但它会抛出:

ValueError: 无法将大小为 1 的数组重新整形为形状 (4,)

【问题讨论】:

标签: python-3.x numpy


【解决方案1】:

您可以使用numpy.newaxis

import numpy as np

a = np.zeros((16, 2))
b = a[:, :, np.newaxis]
c = b.reshape(4, 4, 2)

print(c.shape)

【讨论】:

  • 知道了!我意识到我忘记了什么,谢谢你的回答。
  • a.reshape(4,4,2)np.reshape(a, (4,4,2)) 也可以。您不需要 newaxis 步骤。