一文搞定Numpy基础!

numpy 百度百科传送门

目录

1. 导入numpy并查看版本

import numpy as np

# np.__version__
print(np.__version__)

2. 创建numpy数组

  • 2.1 np.array(list):创建一维数组(向量)
    # np.array(list)
    w = np.array([1, 2, 3])
    
  • 2.2 np.array(list):创建多维数组(矩阵)
    # np.array(list)
    X = np.array(
        [
            [1, 2, 3],
            [4, 5, 6]
        ]
    )
    
  • 2.3 np.zeros(shape, dtype):创建元素值全为0的numpy数组
    # np.zeros(shape, dtype)
    zero = np.zeros(shape=(2, 3), dtype=int)
    
  • 2.4 np.ones(shape, dtype):创建元素值全为1的numpy数组
    # np.ones(shape, dtype)
    one = np.ones(shape=(2, 3), dtype=float)
    
  • 2.5 np.full(fill_value, shape, dtype):创建元素值全为指定元素的numpy数组
    # np.full(fill_value, shape, dtype)
    M = np.full(fill_value=2021, shape=(3, 3), dtype=int)
    

3. numpy区间与区间划分

  • 3.1 np.arange(start, stop, step):区间
    # np.arange(start, stop, step)
    # start 默认为 0
    # step 允许为 float类型
    M = np.arange(start=1, stop=10, step=2)  # [1 3 5 7 9]
    
  • 3.2 np.linspace(start, stop, num):区间划分
    # np.linspace(start, stop, num)
    M = np.linspace(start=0, stop=10, num=5)  # [ 0.   2.5  5.   7.5 10. ]
    

4. numpy中的随机数

  • 4.1 np.random.seed(seed):设置随机种子
    # np.random.seed(seed)
    np.random.seed(2021)
    
  • 4.2 np.random.random(size):随机生成5个(0, 1)之间的浮点数
    # np.random.random(size)
    array_rand = np.random.random(size=5)
    
  • 4.3 np.random.randint(low, high, size):随机生成5个[0, 10)之间的整数
    # np.random.randint(low, high, size)
    array_rand = np.random.randint(low=0, high=10, size=5)
    
  • 4.4 np.random.normal(loc, scale, size):随机生成5个满足正态分布的浮点数
    # np.random.normal(loc, scale, size)
    # loc: 均值
    # scale: 标准差
    array_rand = np.random.normal(loc=0.0, scale=1.0, size=5)
    
  • 4.5 np.random.randn(shape):随机生成5个满足标准正态分布的浮点数
    # np.random.randn(shape)
    # randn方法中的参数应该为生成数组的形状
    # 但查询文档后,未找到该参数的参数名(经测试,shape和size均不正确)
    array_rand = np.random.randn(2, 3)
    
  • 4.6 np.random.shuffle(x):对数组或列表进行乱序处理
    M = np.arange(start=0, stop=5, step=1)  # [0 1 2 3 4]
    
    np.random.seed(2021)
    # np.random.shuffle(x)
    np.random.shuffle(M)
    print(M)  # [2 0 3 1 4]
    

5. numpy数组的常用属性和常用方法

  • 5.1 np.reshape(a, newshape):改变数组形状
    M = np.arange(start=1, stop=7, step=1)
    
    # np.reshape(a, newshape)
    M_23 = np.reshape(a=M, newshape=(2, 3))
    M_23 = np.reshape(a=M, newshape=(2, -1))
    M_23 = np.reshape(a=M, newshape=(-1, 3))
    
  • 5.2 M.shape:查看数组形状
    M = np.arange(start=1, stop=7, step=1).reshape(2, -1)
    
    # M.shape
    print(M.shape)  # (2, 3)
    
  • 5.3 M.size:查看数组元素总数
    M = np.arange(start=1, stop=7, step=1).reshape(2, -1)
    
    # M.size
    print(M.size)  # 6
    
  • 5.4 M.ndim:查看数组维度
    M = np.arange(start=1, stop=7, step=1).reshape(2, -1)
    
    # M.ndim
    print(M.ndim)  # 2
    

6. numpy数组的访问与切片

  • 6.1 数组访问
    M = np.arange(start=1, stop=21, step=1).reshape(4, -1)
    '''
    [[ 1  2  3  4  5]
     [ 6  7  8  9 10]
     [11 12 13 14 15]
     [16 17 18 19 20]]
    '''
    # 访问第3行第2列的元素
    print(M[2][1])  # 12
    
    # 第2行
    print(M[1])  # [ 6  7  8  9 10]
    
    # 第3列
    print(M[:, 2])  # [ 3  8 13 18]
    
  • 6.2 数组切片
    M = np.arange(start=1, stop=21, step=1).reshape(4, -1)
    '''
    [[ 1  2  3  4  5]
     [ 6  7  8  9 10]
     [11 12 13 14 15]
     [16 17 18 19 20]]
    '''
    
    # 前两行,所有列
    print(M[:2, :])
    '''
    [[ 1  2  3  4  5]
     [ 6  7  8  9 10]]
    '''
    
    # 第2、3行,第2、3列
    print(M[1:3, 1:3])
    '''
    [[ 7  8]
     [12 13]]
    '''
    
    # 所有行,奇数列
    print(M[:, ::2])
    '''
    [[ 1  3  5]
     [ 6  8 10]
     [11 13 15]
     [16 18 20]]
    '''
    # 指定列
    col_index = [0, 1, 4]
    print(M[:, col_index])
    '''
    [[ 1  2  5]
     [ 6  7 10]
     [11 12 15]
     [16 17 20]]
    '''
    

7. numpy数组的连接与划分

  • 7.1 np.concatenate(list, axis):数组的连接
    A = np.array([[1, 2], [3, 4]])
    B = np.array([[5, 6], [7, 8]])
    C = np.array([[9, 10], [11, 12]])
    
    # np.concatenate(list, axis)
    # 默认axis=0,忽视x方向(即在垂直方向)进行堆叠
    X = np.concatenate([A, B, C])
    print(X.shape)  # (6, 2)
    
    Y = np.concatenate([A, B, C], axis=1)
    print(Y.shape)  # (2, 6)
    
  • 7.2 np.vstack(list) | np.hstack(list):数组在两个方向上的堆叠
    A = np.array([[1, 2], [3, 4]])
    B = np.array([[5, 6], [7, 8]])
    C = np.array([[9, 10], [11, 12]])
    
    # np.vstack(list):垂直方向上堆叠数组
    X = np.vstack([A, B, C])
    print(X.shape)  # (6, 2)
    
    # np.hstack(list):水平方向上堆叠数组
    Y = np.hstack([A, B, C])
    print(Y.shape)  # (2, 6)
    
  • 7.3 np.split(arr, position_list, axis):数组的拆分
    M = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
    
    # np.split(arr, position_list, axis=0)
    X, Y, Z = np.split(M, [1, 3])
    print(X.shape, Y.shape, Z.shape)  # (1, 4) (2, 4) (1, 4)
    
    # np.split(arr, position_list axis=0)
    A, B = np.split(M, 2, axis=1)
    print(A.shape, B.shape)  # (4, 2) (4, 2)
    
  • 7.4 np.vsplit(arr, list) | np.hsplit(arr, list):数组在两个方向上的拆分
    M = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
    
    # np.vsplit(arr, list)
    x1, x2, x3 = np.vsplit(M, [1, 2])
    print(x1.shape, x2.shape, x3.shape)  # (1, 4) (1, 4) (2, 4)
    
    # np.hsplit(arr, list)
    y1, y2 = np.hsplit(M, 2)
    print(y1.shape, y2.shape)  # (4, 2) (4, 2)
    

8. numpy数组的运算

  • 8.1 基本运算
    M = np.array([[1, 2], [3, 4]])
    
    print(M + 1)  # [[2, 3], [4, 5]]
    print(0 - M)  # [[-1, -2], [-3, -4]]
    print(1.5 * M)  # [[1.5, 3.], [4.5, 6.]]
    print(M / 2)  # [[0.5, 1.], [1.5, 2.]]
    print(M // 3)  # [[0, 0], [1, 1]]
    print(M % 3)  # [[1, 2], [0, 1]]
    print(M ** 2)  # [[1, 4], [9, 16]]
    
    y = np.linspace(0, 3.1415926535, num=7)  # [0, π] / 6
    print(np.sin(y))  # [0., 0.5, 0.866, 1, 0.866, 0.5, 0]
    print(np.cos(y))  # [1, 0.866, 0.5, 0, -0.5, -0.866, -1]
    
    print(np.exp(M))  # [2.71828183, 7.389, 20.086, 54.598]
    print(np.power(M, 3))  # [1, 8, 27, 64]
    
  • 8.2 矩阵运算
    A = np.array([[1, 2], [3, 4]])
    B = np.array([[5, 6], [7, 8]])
    
    # 对应元素相加
    print(A + B)  # [[6, 8], [10, 12]]
    
    # 对应元素相乘
    print(A * B)  # [[5, 12], [21, 32]]
    
    # 矩阵的点乘运算
    print(A.dot(B))  # [[19, 22], [43, 50]]
    print(np.dot(A, B))  # [[19, 22], [43, 50]]
    
    # 矩阵的转置
    print(A.T)  # [[1, 3], [2, 4]]
    print(np.transpose(A))  # [[1, 3], [2, 4]]
    
    # 方阵的逆,非方阵不能求逆
    print(np.linalg.inv(A))  # [[-2., 1.], [1.5, -0.5]]
    print(np.linalg.inv(A).dot(A))  # [[1., 1.], [1., 1.]]
    
    # 矩阵的伪逆(无论是否为方阵,无论是否可逆,均可求)
    C = np.zeros(shape=(2, 3))
    print(np.linalg.pinv(C))  # [[0., 0.], [0., 0.], [0., 0.]]
    
  • 8.3 聚合操作
    M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    
    # 求和
    # 整体聚合运算
    print(np.sum(M))  # 45
    
    # 不同维度上的聚合运算
    # 沿x方向(对列)求和
    print(np.sum(M, axis=0))  # [12 15 18]
    # 沿y方向(对行)求和
    print(np.sum(M, axis=1))  # [ 6 15 24]
    
    # 所有元素乘积
    print(np.prod(M))  # 362880
    
    # 平均数
    print(np.mean(M))  # 5.0
    
    # 中位数
    print(np.median(M))  # 5.0
    
    # 百分位点(当q=50时,即求中位数)
    print(np.percentile(a=M, q=50))  # 5.0
    # 常用百分位点
    for percent in [0, 25, 50, 75, 100]:
        print(percent, np.percentile(M, percent))
    
    # 方差
    print(np.var(M))  # 6.667
    
    # 标准差
    print(np.std(M))  # 2.582
    

9. 其他部分

  • 9.1 arg索引
    M = np.array([4, 7, 1, 3, 8, 0, 6, 2, 9, 5])
    
    # 最小值索引
    print(np.argmin(M))  # 5
    # 最大值索引
    print(np.argmax(M))  # 8
    
    # 排序索引
    # 默认按行排序
    print(np.argsort(M))  # [5 2 7 3 0 9 6 1 4 8]
    
  • 9.2 Fancy Indexing
    X = np.arange(16)
    # 一位数组获取指定索引位置的数据
    index = [3, 5, 8]
    print(X[index])  # [3 5 8]
    
    Y = X.reshape(4, -1)
    # 多维数组获取指定索引位置的数据
    rows = [0, 2, 3]
    cols = [1, 1, 3]
    print(Y[rows, cols])  # [ 1  9 15]
    
  • 9.3 数组的比较
    X = np.arange(16).reshape(4, -1)
    
    # 统计大于3的元素的个数
    print(np.sum(X > 3))  # 12
    
    # 统计非零元素的个数
    print(np.count_nonzero(X))  # 15
    
    # 判断是否存在任意一个元素满足条件
    print(np.any(X == 0))  # True
    print(np.any(X == 16))  # False
    print(np.any(X < 0))  # False
    print(np.any(X > 10))  # True
    
    # 判断是否所有元素满足条件
    print(np.all(X > 0))  # False
    print(np.all(X >= 0))  # True
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值