首页 > 解决方案 > numpy,使用赋值语句改变数组的形状来改变形状属性的行为与使用 reshape 时不同

问题描述

我对以下两种改变 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 的浅拷贝。

标签: numpy

解决方案


推荐阅读