补充: shape 属性
#参数是一个数时,返回空
>>> import numpy as np
>>> np.shape(0)
()
#参数是一维矩阵 返回的是一维数组的大小
>>> np.shape([1])
(1,)
>>> np.shape([1, 2])
(2,)
# 参数是二维矩阵
>>> np.shape([[1],[2]])
(2, 1)
>>> np.shape([[1, 2], [2, 3], [3, 4]])
(3, 2)
#直接用.shape可以快速读取矩阵的形状,使用shape[0]读取矩阵第一维度的长度
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> a.shape
(3, 3)
>>> a.shape[0]
3
>>> a.shape[1]
3
#但是当某一维度长度不一致时,读取所有维度时则不能读出长短不一致的维度
>>> a = np.array([[1, 2, 3], [4, 5], ])
>>> a.shape
>>> a.shape[0]
2
>>> a.shape[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
(2,)
补充: reshape函数
-
numpy.arange(n).reshape(a, b) 依次生成n个自然数,并且以a行b列的数组形式显示
In [2]: np.arange(16).reshape(2,8) Out[2]: array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15]])
-
reshape(-1)
In [4]: z.reshape(-1)
Out[4]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
- reshape(-1, 1)
为了使列数变为1列,NumPy自动算出有16行
In [5]: z.reshape(-1,1)
Out[5]:
array([[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12],
[13],
[14],
[15]])
- reshape(-1, 2)
同理:reshape后的shape等于(8, 2)
z.reshape(-1,2)
Out[6]:
array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11],
[12, 13],
[14, 15]])
省略号应用
>>> x = numpy.arange(12).reshape(-1,4)
>>> x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x[...,1] # 第二列元素
array([1, 5, 9])
>>> x[1,...] # 第二行元素
array([4, 5, 6, 7])
>>> x[...,1:] # 第二列元素以及剩余元素
array([[ 1, 2, 3],
[ 5, 6, 7],
[ 9, 10, 11]])
>>> x[:2,...] # 第1,2行元素
array([[0, 1, 2, 3],
[4, 5, 6, 7]])