1.ndarray对象

1.1 属性

属性名字 属性解释
ndarray.shape 数组维度的元组
ndarray.ndim 数组维数
ndarray.size 数组中的元素数量
ndarray.itemsize 一个数组元素的长度(字节)
ndarray.dtype 数组元素的类型

2. 数组生成

2.1 linspace(等差数组)

  • 描述

numpy.linspace 函数用于创建一个一维数组,数组是一个等差数列构成的(指定数量)

  • 用法

np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

  • 参数 | start | 序列的起始值 | | —- | —- | | stop | 序列的终止值,如果endpointtrue,该值包含于数列中 | | num | 要生成的等步长的样本数量,默认为50 | | endpoint | 该值为 true 时,数列中包含stop值,反之不包含,默认是True。 | | retstep | 如果为 True 时,生成的数组中会显示间距,反之不显示。 | | dtype | ndarray 的数据类型 |

  • 返回值

返回一个ndarray数组,数组内元素的类型为numpy.float64

  • 用法

    1. import numpy as np
    2. a = np.linspace(1,10,10)
    3. print(a)
    4. # [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]

    2.2 生成0/1数组

  • 描述

生成全0或全1的数组

  • 用法
    • np.ones(shape, dtype)
    • np.ones_like(a, dtype)
    • np.zeros(shape, dtype)
    • np.zeros_like(a, dtype)
  • 参数 | shape:列表 | 生成的数组形状 | | —- | —- | | a:array_like | 生成与数组a形状相同的数组 | | dtype:np.dtype | 数据类型,默认为浮点数 |

  • 返回值

ndarray

2.3 从现有数组生成

  • 描述

从已有的数组生成一个ndarray数组,有两种方法,这两种略有不同

  • 用法
    • np.array(array_like)
    • np.asarray(array_like)
  • 参数 | array_like | 用于生成ndarray数组的列表或数组 | | —- | —- |

  • 二者区别

array属于深拷贝,即他是复制一份新的数组用于生成
而asarray属于浅拷贝,即他是直接用原有数组的内存空间生成
所以当原有数组里的元素修改时,array生成的数组不会变化,而asarray生成的数组的元素会随着变化

2.4 arange(等差数组)

  • 描述

创建等差数组。(指定步长

  • 用法

np.arange(start,stop, step, dtype)

  • 参数 | start | 序列起始值 | | —- | —- | | stop | 序列终止值 | | step | 步长 |

2.5 logspace (等比数列)

  • 描述

创建等比数列数组

  • 用法

    np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

  • 参数 | 参数 | 描述 | | :—- | :—- | | start | 序列的起始值为:base start | | stop | 序列的终止值为:base stop。如果endpointtrue,该值包含于数列中 | | num | 要生成的等步长的样本数量,默认为50 | | endpoint | 该值为 true 时,数列中中包含stop值,反之不包含,默认是True。 | | base | 对数 log 的底数。 | | dtype | ndarray 的数据类型 |

注意:start和stop相当于等比数列的次数,base即等比数列的基数,默认为10

  • 示例

    1. np.logspace(0, 4, 5, base=2)
    2. # array([ 1., 2., 4., 8., 16.])

    2.5 随机数组生成

    使用np.random模块

    2.5.1 正态分布

    正态分布记作Numpy - 图1Numpy - 图2决定了其位置,其标准差Numpy - 图3决定了分布的幅度。当Numpy - 图4时的正态分布是标准正态分布。标准差Numpy - 图5越大,则正态分布图像开口越大。

  • np.random.normal(loc=0.0,scale=1.0,size=None)

    • loc:float

此概率分布的均值(对应着整个分布的中心centre)

  • scale:float

此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高)

  • size:int or tuple of ints

输出的shape,默认为None,只输出一个值

  • np.random.standard_normal(size=None)

返回指定形状的标准正态分布的数组。

2.5.2 均匀分布

  • np.random.randn(d0,d1,d2...)

创建给定形状的数组,并使用上均匀分布的随机数填充数组,随机数范围在Numpy - 图6,d0,d1,d2..指的是数组的维度。

注意:参数只能填int数,不能填列表或元组

  • np.random.uniform(low=0.0, high=1.0, size=None)
    • low: 采样下界,float类型,默认值为0;
    • high: 采样上界,float类型,默认值为1;
    • size: 输出样本数目,为int或元组(tuple)类型,例如,size=(m,n,k), 则输出m_n_k个样本,缺省时输出1个值。
  • np.random.randint(low, high=None, size=None, dtype='l')
    • 一个均匀分布中随机采样,生成一个整数或N维整数数组,
    • 取数范围:若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。

3. 数学函数与数组运算

3.1 三角函数

  • 描述

计算三角函数值

  • 用法

np.sin(x)np.cos(x)

  • 参数 | x: array_like | 一个类数组,列表、元组、adarray等 | | —- | —- |

  • 返回值

返回一个array_like数组

3.2 通用判断函数

  • np.all(判断语句)

对判断语句中数组的所有元素进行判断,如果全部为True,返回True,否则返回False

  • np.any(判断语句)

对判断语句中数组的所有元素进行判断,如果存在True,返回True,如果全是False返回False

  • 示例
    1. score = np.random.randint(30,100,(5,4))
    2. #array([[96, 63, 35, 80],
    3. # [72, 84, 39, 92],
    4. # [77, 61, 91, 72],
    5. # [50, 67, 76, 48]])
    6. np.all(score[0:2] > 60) # False
    7. np.any(score[0:2] > 60) # True

    注意:这里返回的是一个bool值,不是一个ndarray


3.3 where(三元运算符)

这个函数类似于for循环遍历数组的所有元素,然后根据判断条件(True/False)对其进行修改

  • 用法

np.where(逻辑判断,true_value, false_value)

  • 参数 | 逻辑判断 | 是指对数组的每个元素按条件进行判断转化成bool值 | | —- | —- | | true_value | 如果对应位置上的bool值是true,则转化成true_value | | false_value | 如果是False,则替换成false_value |

  • 返回值

返回修改过后的ndarray。

  • 示例 ```python temp

    array([[96, 63, 35, 80],

    [72, 84, 39, 92]])

    np.where(temp>60,’及格’,’不及格’)

    array([[‘及格’, ‘及格’, ‘不及格’, ‘及格’],

    [‘及格’, ‘及格’, ‘不及格’, ‘及格’]], dtype=’<U3’)

np.where(np.logical_or(temp>80,temp<60),1,0)

array([[1, 0, 1, 0],

[0, 1, 1, 1]])

np.where(np.logical_and(temp>70,temp<90),1,0)

array([[0, 0, 0, 1],

[1, 1, 0, 0]])

  1. ---
  2. <a name="JxkJj"></a>
  3. ## 3.4 统计运算
  4. - `min(a, axis)` # 最小值
  5. - Return the minimum of an array or minimum **along an axis**.
  6. - `max(a, axis])` # 最大值
  7. - Return the maximum of an array or maximum along an axis.
  8. - `median(a, axis)` # 中位数
  9. - Compute the median along the specified axis.
  10. - `mean(a, axis, dtype)` # 平均值
  11. - Compute the arithmetic mean along the specified axis.
  12. - `std(a, axis, dtype)` # 标准差 =方差开根
  13. - Compute the standard deviation along the specified axis.
  14. - `var(a, axis, dtype)` # 方差
  15. - Compute the variance along the specified axis.
  16. **axis 0代表列, axis 1代表行去进行统计, 如果不指定轴,则是对整个数组元素进行操作****。**
  17. - 示例
  18. ```python
  19. array([[96, 63, 35, 80],
  20. [72, 84, 39, 92],
  21. [36, 57, 94, 46],
  22. [77, 61, 91, 72],
  23. [50, 67, 76, 48]])
  24. np.max(score,axis=0) # array([96, 84, 94, 92])
  25. np.max(score,axis=1) # array([96, 92, 94, 91, 76])
  26. np.max(score) # 96

  • np.argmax(temp, axis=)
  • np.argmin(temp, axis=)
    • 不是返回最大/最小值,而是返回下标。
  • 示例
    array([[96, 63, 35, 80],
         [72, 84, 39, 92],
         [36, 57, 94, 46],
         [77, 61, 91, 72],
         [50, 67, 76, 48]])
    np.argmin(score) # 2
    np.argmin(score,  axis=1) #array([2, 2, 0, 1, 3], dtype=int64)
    

    注意:下标不是类似于索引的形式,而是一行一行数,数它是第几个元素。

3.5 广播机制

满足一下任一条件即可广播

  • 1.数组的某一维度等长
  • 2.其中一个数组的某一维度为1

    且数组之间的加减乘除数学运算是对每个元素进行运算,与列表不一样,列表的乘(*)是复制元素

3.6 矩阵乘法

  • np.matmul(矩阵A,矩阵B)
  • np.dot

二者都是矩阵乘法。 np.matmul禁止矩阵与标量的乘法。 在矢量乘矢量的內积运算中,np.matmulnp.dot没有区别。其实矩阵与标量的乘法就是ndarray*scale

3.7 np.argmax()

numpy.argmax(array, axis) 用于返回一个numpy数组中最大值的索引值。当一组中同时出现几个最大值时,返回第一个最大值的索引值。

one_dim_array = np.array([1, 4, 5, 3, 7, 2, 6])
print(np.argmax(one_dim_array)) # 4
#--------------------------------------
two_dim_array = np.array([[1, 3, 5], [0, 4, 3]])
max_index_axis0 = np.argmax(two_dim_array, axis = 0)
max_index_axis1 = np.argmax(two_dim_array, axis = 1)
print(max_index_axis0) # [0 1 0] 
print(max_index_axis1) # [2 1]

4. 数组形状/类型修改

4.1 resize

  • 描述

将数组修改成指定的形状,如果修改后的形状大于原先形状,则自动填充,有两种调用方式,其填充不同

  • 用法
    • np.resize(a, new_shape)
    • ndarray.resize(new_shape),是in-place操作,即在数组内存空间引用上修改
  • 参数 | a:array_like | Array to be resized. | | —- | —- | | new_shape:int or tuple of int | Shape of resized array. |

注意:np.resize在元素不足时复制原数组的元素进行填充,而ndarray.resize填充的是0。

  • 返回值

np.resize会返回修改后的新数组

4.2 reshape

  • 描述

resize类似,但当修改后的形状大于原形状,无填充能力。可自己选择以什么样的顺序去填充新的数组

  • 用法
    • np.reshape(a, newshape, order='C')
    • ndarray.reshape(newshape, order='C')
  • 参数 | a:array_like | Array to be resized. | | —- | —- | | new_shape:int or tuple of int | Shape of resized array.允许存在-1,此时-1维度由程序自己推出 | | order:{‘C’,‘F’,‘A’}, ``optional | ‘C’的意思就是说按照索引顺序横着读取原数组元素,然后按照行的顺序写入新数组,’F’则是(列)着读,竖(列)着写 |

  • 示例

    old = np.arange(0, 6).reshape((2,3))
    #array([[0, 1, 2],
    #      [3, 4, 5]])
    new = np.reshape(old, (3,2),'F') #列读取/写入
    #array([[0, 4],
    #       [3, 2],
    #       [1, 5]])
    new = np.reshape(old, (3,2),'C') #行读取/写入
    #array([[0, 1],
    #       [2, 3],
    #       [4, 5]])
    

    4.3 转置

  • ndarray.T

将数组的行列进行互换

4.4 类型修改

  • ndarray.astype(type)

返回修改了类型之后的数组,原数组不变

4.5 vstack

垂直方向行顺序)堆叠数组构成一个新的数组。就是一行一行的放。

a = np.array([1,2,3]) # array([1, 2, 3])
np.vstack(a) 
#array([[1],
#       [2],
#       [3]])
b = np.array([4,5,6])
np.vstack([a,b])
# array([[1, 2, 3],
#        [4, 5, 6]])