Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 重塑仅具有一维的numpy数组_Python_Numpy_Reshape - Fatal编程技术网

Python 重塑仅具有一维的numpy数组

Python 重塑仅具有一维的numpy数组,python,numpy,reshape,Python,Numpy,Reshape,为了从列表中获取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],

为了从
列表
中获取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元素
我如何重塑我的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.arange(12)
是一种不太优雅的说法

其次,您可以将
-1
传递到重塑的一维(函数和方法)。在您的情况下,如果您知道总大小是3的倍数,请执行以下操作:

np.arange(12).reshape(-1, 3)
要获得4x3阵列。从文档中:

一个形状标注可以是-1。在这种情况下,将根据数组的长度和剩余维度推断该值


作为旁注,出现错误的原因是,即使对于整数,正则除法也会自动导致Python 3中的
float
type(12/3)
is
float
。您可以通过执行
a.shape[0]//3
来使用整数除法,从而使原始代码正常工作。也就是说,使用
-1
要方便得多。

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

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

[1]

int(a.shape[0]/3)
应该doa。重塑(-1,3)更重要general@nsaura的确,你是right@Dav2357.
a.shape[0]//3
如果你坚持走这条路,会更优雅。最好使用
arange
然后在这里使用
numpy
时列出理解