5-Python-NumPy中shape和reshape的区别
2020-10-15 本文已影响0人
千千罐
shape 和 reshape 的区别:
- shape 直接更改原数组的结构 a.shape = (n,m)
- reshape 不能对原数组进行操作,需要重新赋值给新的数组 b=a.reshape(n,m)
- reshape 生成的新数组b,如果改变b里面元素的值,a的值也会更着改变
示例如下:
>>> 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]])