鉴于我有一个 2d 数组,我想将它重塑为 1d,每行一个值

Given that i have a 2d array and i want to reshape it to 1d with one value per row

这是我的数组

arr = np.array([[0, 1],
[3, 4],
[6, 7]])

flat_arr = np.reshape(arr, -1)

我得到以下结果:

[0 1 2 3 4 5 6 7 8]

我想要的结果是:

[0]
[1]
[3]
[4]
[5]...

有几种方法可以做到:

flat_arr[:, None]
flat_arr[:, np.newaxis]
np.expand_dims(flat_arr, axis=1)

此外,您可以像这样重塑它:

arr.reshape(-1, 1)

您可以使用这个新形状:

import numpy as np

arr = np.array([[0, 1], [3, 4], [6, 7]])

flat_arr = np.reshape(arr, (arr.shape[0] * arr.shape[1], 1))

print(flat_arr)

输出:

[[0]
 [1]
 [3]
 [4]
 [6]
 [7]]

此外,正如@MarkMeyer 所添加的,您可以使用:

flat_arr = np.reshape(arr, (-1, 1))