美文网首页Python 之道
Python 学习笔记之 Numpy 库——数组基础

Python 学习笔记之 Numpy 库——数组基础

作者: seniusen | 来源:发表于2018-10-01 15:34 被阅读2次

    1. 初识数组

    import numpy as np
    a = np.arange(15)
    a = a.reshape(3, 5)
    print(a.ndim, a.shape, a.dtype)
    # 2 (3, 5) int64
    print(a.size, a.itemsize) # 15 8
    
    • ndim,数组的维度数,二维数组就是 2
    • shape,数组在各个维度上的长度,用元组表示
    • dtype,数组中元素的数据类型,比如 int32, float64 等
    • size,数组中所有元素的总数
    • itemsize,数组中每个元素所占的字节数

    2. 创建数组

    a = np.array([[1, 2, 3], [4, 5, 6]])
    a = np.ones((3, 4))
    a = np.zeros((3, 4), dtype=np.int32)
    a = np.linspace(0, 2, 9)   
    # 9 numbers from 0 to 2
    
    • np.linspace(start, stop, num=50) 产生一个区间在[start, stop],长度为 num 的一维数组

    3. 基本运算

    a = np.array([[1, 2, 3], [4, 5, 6]]) 
                           # (2, 3)
    b = np.array([[1, 0, 1], [0, 1, 1],
     [1, 1, 0]])           # (3, 3)
    
    c = np.dot(a, b)       # 矩阵相乘
    d = a @ b              # 矩阵相乘
    e = np.dot(a[0], a[0]) # 向量内积
    f = a * a              # 元素相乘
    
    g = np.sum(a)
    h = np.mean(a, axis=0)
    
    • np.sum 等函数若不指定 axis,则把数组所有元素当成列表来处理,axis = 0,表示只在第一个维度上进行求和,以此类推。

    4. 维度操作

    a = np.zeros((2, 3))
    b = np.zeros((3, 3))
    np.vstack((a, b)).shape  # (5, 3)
    
    • np.vstack, 沿着垂直方向或者行的方向将数组堆起来
    a = np.zeros((2, 1, 5))
    b = np.zeros((2, 2, 5))
    np.hstack((a, b)).shape  # (2, 3, 5)
    
    • np.hstack, 沿着水平方向或者列的方向将数组堆起来
    a = np.zeros((2, 5, 1))
    b = np.zeros((2, 5, 5))
    np.concatenate((a, b), axis=2).shape  
    # (2, 5, 6)
    
    • np.concatenate, 沿着某一维度将数组堆起来
    a = np.zeros((3, ))
    b = np.zeros((3, ))
    np.stack((a, b), axis=0).shape #(2, 3)
    np.stack((a, b), axis=1).shape #(3, 2)
    
    • np.stack, 将数组沿着新的维度堆起来

    5. 随机数

    a = np.random.rand(3, 2)  # (3, 2)
    
    • np.random.rand, 返回一个 [0, 1) 之间的随机分布
    a = np.random.random((2, 3)) # (2, 3)
    
    • np.random.random, 返回一个 [0, 1) 之间的随机分布
    a = np.random.randn(3, 2)  # (3, 2)
    a = sigma * np.random.randn(...) + mu 
    
    • np.random.randn, 返回一个均值为 0 方差为 1 的标准正态分布,通过 mu 和 sigma 可以任意改变均值和方差
    a = np.random.randint(1, 5, (3, 2))  
    # (3, 2)
    
    • np.random.randint(low, high=None, size=None), 返回一个 [0, low) 或者 [low, high) 之间的随机整数
    a = np.arange(5, 10)
    np.random.choice(a, 3, replace=False)
    np.random.choice(5, (3,2))
    
    • np.random.choice(a, size=None, replace=True, p=None), 返回 a 中元素或者 np.arange(a) 范围内的随机整数,replace=True 默认可以有重复元素
    np.random.seed(1)
    a = np.random.rand(3, 2)
    np.random.seed(1)
    b = np.random.rand(3, 2) # a == b
    
    a = np.array([1, 2, 3, 4, 5])
    np.random.shuffle(a) 
    
    • np.random.seed 通过设置随机数种子的值可以保证两次产生的随机数相同
    • np.random.shuffle() 沿着第一维随机打乱数组

    获取更多精彩,请关注「seniusen」!


    seniusen

    相关文章

      网友评论

        本文标题:Python 学习笔记之 Numpy 库——数组基础

        本文链接:https://www.haomeiwen.com/subject/tuqnoftx.html