Skip to main content
 首页 » 编程设计

python之reshape 只有一维的numpy数组

2025年05月04日24bjzhanghao

为了从 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]]) 

但是如果我知道我将在初始 list 中有 3 * n 个元素,我该如何 reshape 我的 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 和方法 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.

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