Python中reshape函数参数-1的使用

个人认为这是为了偷懒而设计的,为什这么说呢,假设你有a=[1 2 3 4 5 6 7 8 9 10]这样的一维数组,你只想让a变成2列的二维数组。按照常规的reshape,你得计算他的行数,经计算reshape的参数为reshape(5,2)。而使用reshape(-1,2),他会利用a和2列,计算出行数为5。还是举个例子比较清楚

>>> import numpy as np
>>> a=np.array([1,2,3,4,5,6,7,8,9,10])
>>> a.shape
(10,)
>>> a.reshape(5,2)
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
>>> #假设我们需要的是2列二维数组,又不想计算行数是多少可用reshape(-1,2)
>>> a.reshape(-1,2)
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
>>> #有结果可知他也得到了(5,2)二维数组,同理你想要得到是5行的二维数组时
>>> a.reshape(5,-1)
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
>>> 

猜你喜欢

转载自blog.csdn.net/qq_29023939/article/details/81053124