重塑只有一维的numpy数组

Reshape numpy array having only one dimension

为了从 list 中获取一个 numpy 数组,我做了以下操作:

np.array([i for i in range(0, 12)])

并得到:

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

然后我想从这个数组中创建一个 (4,3) 矩阵:

np.array([i for i in range(0, 12)]).reshape(4, 3)

我得到以下矩阵:

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

但是如果我知道初始 3 * n 个元素 list 我该如何重塑我的 numpy 数组,因为下面的代码

np.array([i for i in range(0,12)]).reshape(a.shape[0]/3,3)

导致错误

TypeError: 'float' object cannot be interpreted as an integer

首先,np.array([i for i in range(0, 12)]) 是一种不太优雅的说法 np.arange(12)

其次,可以将-1传给reshape的一维(都是np.reshape and the method np.ndarray.reshape函数)。在您的情况下,如果您知道总大小是 3 的倍数,则执行

np.arange(12).reshape(-1, 3)

得到一个 4x3 数组。来自文档:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

附带说明一下,出现错误的原因是常规除法,即使是整数,也会自动导致 float in Python 3: type(12 / 3) is float。您可以通过 a.shape[0] // 3 改为使用整数除法来使您的原始代码正常工作。也就是说,使用 -1 更方便。

您可以在 .reshape 中使用 -1。如果您指定一个维度,Numpy 将在可能的情况下自动确定另一个维度[1]。

np.array([i for i in range(0,12)]).reshape(-1, 3)

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html