numpy 辨异(一) —— reshape 与 resize

0. reshape的参数

reshape的参数严格地说,应该是tuple类型(tuple of ints),似乎不是tuple也成(ints)。

>>> x = np.random.rand(2, 3)
>>> x.reshape((3, 2))
                                    # 以tuple of ints
array([[ 0.19399632,  0.33569667],
       [ 0.36343308,  0.7068406 ],
       [ 0.89809989,  0.7316493 ]])
>>> x.reshape(3, 2)
array([[ 0.19399632,  0.33569667],
       [ 0.36343308,  0.7068406 ],
       [ 0.89809989,  0.7316493 ]])

1. .reshape 实现维度的提升

(3, ) (3, 1):前者表示一维数组(无行和列的概念),后者则表示一个特殊的二维数组,也即是一个列向量;

>> x = np.ones(3)
>> x
array([ 1.,  1.,  1.])
>> x.reshape(3, 1)
array([[ 1.],
       [ 1.],
       [ 1.]])
>> x.reshape(1, 3)
array([[ 1.,  1.,  1.]])

2. .reshape.resize

  • reshape:有返回值,所谓有返回值,即不对原始多维数组进行修改;
  • resize:无返回值,所谓有返回值,即会对原始多维数组进行修改;
>> X = np.random.randn(2, 3)
>> X
array([[ 1.23077478, -0.70550605, -0.37017735],
       [-0.61543319,  1.1188644 , -1.05797142]])

>> X.reshape((3, 2))
array([[ 1.23077478, -0.70550605],
       [-0.37017735, -0.61543319],
       [ 1.1188644 , -1.05797142]])

>> X
array([[ 1.23077478, -0.70550605, -0.37017735],
       [-0.61543319,  1.1188644 , -1.05797142]])

>> X.resize((3, 2))
>> X
array([[ 1.23077478, -0.70550605],
       [-0.37017735, -0.61543319],
       [ 1.1188644 , -1.05797142]])

你可能感兴趣的:(numpy 辨异(一) —— reshape 与 resize)