参考:
https://blog.csdn.net/weixin_43216017/article/details/87266388https://blog.csdn.net/u012005313/article/details/49383551?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.channel_paramhttps://www.cnblogs.com/onemorepoint/p/9099312.html
在Numpy中,shape和reshape()函数很常用。二者的功能都是对于数组的形状进行操作。shape函数可以了解数组的结构;reshape()函数可以对数组的结构进行改变。
1. shape
import numpy
as np
a
= np
.array
([1,2,3,4,5,6,7,8])
a
.shape
'''结果:(8,)'''
type(a
.shape
) '''结果:tuple'''
a
.shape
[0] '''结果:8'''
import numpy
as np
a
= np
.array
([1,2,3,4,4,3,2,8])
a1
= np
.array
([[1,2,3,4],[4,3,2,8]])
print(a
.shape
[0])
print(a1
.shape
[0])
print(a1
.shape
[1])
由上代码可以看出: 一维数组的时候:shape是读取数组的数据个数。 二维数组的时候:shape[0]读取的是矩阵的行数,shape[1]读取的是矩阵的列数。
2. reshape()
输入参数: a:将要被重塑的类数组或数组; newshape:整数值或整数元组。新的形状应该兼容于原始形状。如果是一个整数值,表示一个一维数组的长度;如果是元组,一个元素值可以为-1,此时该元素值表示为指定,此时会从数组的长度和剩余的维度中推断出; order:可选(忽略)返回:一个新的形状的数组。
a
=array
([[1,2,3],[4,5,6]])
reshape
(a
, 6)
reshape
(a
, (3, -1))
a
= np
.array
([1,2,3,4,5,6,7,8])
a
.reshape
(2,4)
'''结果:array([[1, 2, 3, 4],
[5, 6, 7, 8]])
'''
a
.reshape
(4,2)
'''结果:
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
'''
z
= np
.array
([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
z
.shape
(4, 4)
z
.reshape
(-1)
array
([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
z
.reshape
(-1, 1)
array
([[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12],
[13],
[14],
[15],
[16]])
z
.reshape
(-1, 2)
array
([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12],
[13, 14],
[15, 16]])
reshape()函数可以改变数组的形状,并且原始数据不发生变化。
但是,reshape()函数中的参数需要满足乘积等于数组中数据总数。如:当我们将8个数使用(2,3)重新排列时,python会报错。
而且,reshape()函数得出的数组与原数组使用的是同一个存储空间,改变一个,另一个也随之改变。 注意:shape和reshape()函数都是对于数组(array)进行操作的,对于list结构是不可以的。