numpy,使用赋值语句对shape属性进行更改来改变数组的形状与使用reshape时的行为有所不同

时间:2019-04-07 13:54:27

标签: numpy

我对以下两种改变numpy数组形状的方式的不同行为感到困惑:

x.shape = (3,4)    
x = x.reshape(3,4)

这里是一个例子:

In [1]: import numpy as np
##### Case 1
In [2]: fa = np.arange(12).reshape(4,3)
In [3]: x = fa
In [4]: x is fa
Out[4]: True
In [5]: x.shape = (3,4)         # RESHAPING does not affect x 
In [6]: x is fa
Out[6]: True
########Case 2 ########
In [7]: fa = np.arange(12).reshape(4,3)
In [8]: x = fa
In [11]: x.reshape(3,4) is fa   # RESHAPING makes x a shallow copy
Out[11]: False
########Verify x is shallow copy
In [13]: fa = np.arange(12).reshape(4,3)
In [14]: x.reshape(3,4).base is fa.base
Out[14]: True

对于第一种重塑时x仍然与fa相同,但是在第二种重塑后x变为fa的浅表副本的原因,我无法理解。

0 个答案:

没有答案