5-Python-NumPy中shape和reshape的区别

2020-10-15  本文已影响0人  千千罐
shapereshape 的区别:

示例如下:

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> a.shape=(3,2)          #直接在a的基础上进行修改
>>> a
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> a.reshape=(3,2)      #reshape 不能和shape同样的操作,会提示错误
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object attribute 'reshape' is read-only

>>> b = a.reshape(3,2)       #使用reshape需要重新赋值
>>> b
array([[1, 2],
       [3, 4],
       [5, 6]])

>>> b[0,0] = 100            #更改b[0,0]元素的值
>>> b
array([[100,   2],
       [  3,   4],
       [  5,   6]])
>>> a                       #可以发现a[0,0]元素也发生了改变
array([[100,   2],
       [  3,   4],
       [  5,   6]])
上一篇下一篇

猜你喜欢

热点阅读