zoukankan      html  css  js  c++  java
  • day18

    numpy模块

    • 定义:numpy是python的一种开源的数值计算扩展库。用来存储和处理大型numpy数组(矩阵)

    • numpy库有两个作用:

    1. 区别于list列表,提供了数组操作、数组运算、以及统计分布和简单的数学模型。
    2. 计算速度快,甚至要由于python内置的简单运算,使得其成为pandas、sklearn等模块的依赖包。高级的框架如TensorFlow、pyTorch等,其数组操作和numpy非常相似。

    创建numpy数组

    import numpy as np
    
    # 创建一维的ndarray对象
    arr = np.array([1, 2, 3])
    print(arr, type(arr))
    # [1 2 3] <class 'numpy.ndarray'>
    
    
    # 创建二维的ndarray对象     最常用**
    print(np.array([[1, 2, 3], [4, 5, 6]]))
    # [[1 2 3]
    # [4 5 6]]
    
    
    # 创建三维的ndarray对象
    print(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
    # [[1 2 3]
    # [4 5 6]
    # [7 8 9]]
    

    numpy数组的常用属性

    dtype数据类型:bool_, int(8,16,32,64) , float(16,32,64)

    # 新建numpy数组,数据类型为float32
    arr = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
    print(arr)
    
    # [[1. 2. 3.]
    #  [4. 5. 6.]]
    

    dtype 查看数组元素的数据类型

    print(arr.dtype)
    
    # float32
    

    astype:数据类型转换

    arr = arr.astype(np.int32)
    print(arr.dtype)
    print(arr)
    
    # int32
    # [[1 2 3]
    #  [4 5 6]]
    

    T:数组的转置(行列互换)

    print(arr.T)
    
    # [[1. 4.]
    #  [2. 5.]
    #  [3. 6.]]
    

    size:查看数组元素的个数

    print(arr.size)
    
    # 6
    

    ndim:查看数组的维数

    print(arr.ndim)
    
    # 2
    

    shape:查看数组的维度大小(行,列)元组形式

    print(arr.shape)
    
    # (2, 3)
    

    获取numpy二数组行列数

    获取numpy数组的行和列构成的数组

    # 新建numpy二维数组
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    print(arr)
    [[1 2 3]
     [4 5 6]]
    
    print(arr.shape)
    
    # (2, 3)
    

    获取numpy数组的行

    # 获取numpy数组的行
    print(arr.shape[0])
    
    # 2
    

    获取numpy数组的列

    print(arr.shape[1])
    
    # 3
    

    切割numpy数组

    切分numpy数组类似于列表的切割,但是与列表的切割不同的是,numpy数组的切割涉及到行和列的切割,但是两者切割的方式都是从索引0开始,并且取头不取尾。

    取所有元素

    # 新建二维数组
    arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
    print(arr)
    '''[[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]]'''
    
    
    print(arr[:, :])  # [行,列]
    
    '''[[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]]'''
    

    取第一行的所有元素

    print(arr[:1, :])
    # [[1 2 3 4]]
    
    print(arr[0, [0, 1, 2, 3]])
    # [1 2 3 4]
    

    取第一列的所有元素

    print(arr[:, :1])
    # [[1]
    #  [5]
    #  [9]]
    
    
    print(arr[(0, 1, 2), 0])
    # [1 5 9]
    

    取第一行第一列的元素

    print(arr[(0, 1, 2), 0])
    # [1 5 9]
    
    
    print(arr[0, 0])
    # 1
    

    取大于5的元素,返回一个数组

    print(arr[arr > 5])
    # [ 6  7  8  9 10 11 12]
    

    numpy数组元素替换

    取第一行的所有元素,并且让第一行的元素都为0

    arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
    print(arr)
    '''[[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]]'''
    
    arr1 = arr.copy()
    arr1[:1, :] = 0
    print(arr1)
    '''[[ 0  0  0  0]
     [ 5  6  7  8]
     [ 9 10 11 12]]'''
    

    取所有大于5的元素,并且让大于5的元素为0

    arr2 = arr.copy()
    arr2[arr > 5] = 0
    print(arr2)
    
    '''[[1 2 3 4]
     [5 0 0 0]
     [0 0 0 0]]'''
    

    对numpy数组清零

    arr3 = arr.copy()
    arr3[:, :] = 0
    print(arr3)
    
    '''[[0 0 0 0]
     [0 0 0 0]
     [0 0 0 0]]'''
    

    numpy数组的合并

    # 新建两个二维数组
    arr1 = np.array([[1, 2], [3, 4], [5, 6]])
    print(arr1)
    '''[[1 2]
     [3 4]
     [5 6]]'''
    
    arr2 = np.array([[7, 8], [9, 10], [11, 12]])
    print(arr2)
    '''[[ 7  8]
     [ 9 10]
     [11 12]]'''
    

    合并两个numpy数组的行

    # 注意使用hstack()方法合并numpy数组,numpy数组应该有相同的行
    print(np.hstack((arr1, arr2)))
    
    '''[[ 1  2  7  8]
     [ 3  4  9 10]
     [ 5  6 11 12]]'''
    

    合并两个numpy数组的列

    # 注意使用vstack()方法合并numpy数组,numpy数组应该有相同的列
    print(np.vstack((arr1, arr2)))
    '''[[ 1  2]
     [ 3  4]
     [ 5  6]
     [ 7  8]
     [ 9 10]
     [11 12]]'''
    

    合并两个numpy数组

    # 合并两个numpy数组,其中axis=1表示合并两个numpy数组的行
    print(np.concatenate((arr1, arr2), axis=1))
    '''[[ 1  2  7  8]
     [ 3  4  9 10]
     [ 5  6 11 12]]'''
    
    # 合并两个numpy数组,其中axis=0表示合并两个numpy数组的列
    print(np.concatenate((arr1, arr2), axis=0))
    '''[[ 1  2]
     [ 3  4]
     [ 5  6]
     [ 7  8]
     [ 9 10]
     [11 12]]'''
    

    numpy常用函数

    array():将列表转换为数组,可选择显式指定dtype

    arr = np.array([1, 2, 3])  # 创建一维数组
    print(arr)
    
    # [1 2 3]
    

    arange():range的numpy版,支持浮点数

    # 构造0-9的ndarray数组            [0 1 2 3 4 5 6 7 8 9]
    print(np.arange(10))
    
    # 构造1-4的ndarray数组            [1 2 3 4]
    print(np.arange(1, 5))
    
    # 构造1-19且步长为2的ndarray数组   [ 1  3  5  7  9 11 13 15 17 19]
    print(np.arange(1, 20, 2))
    

    linspace():类似arange(),第三个参数为数组长度

    # 构造一个等差数列,取头也取尾,从0取到20,取5个数
    print(np.linspace(0, 20, 5))
    # [ 0.  5. 10. 15. 20.]
    
    
    # 构造一个数列,取头也取尾,从1取到100,取10个数
    print(np.linspace(1, 100, 10))
    # [  1.  12.  23.  34.  45.  56.  67.  78.  89. 100.]
    

    zeros():根据指定形状和dtype创建全0数组

    # 创建一个2*3的全0数组
    print(np.ones((2, 3)))
    '''[[1. 1. 1.]
     [1. 1. 1.]]'''
    

    ones():根据指定形状和dtype创建全1数组

    # 创建一个2*3的全1数组
    print(np.zeros((2, 3)))
    '''[[0. 0. 0.]
     [0. 0. 0.]]'''
    

    eye():创建单位矩阵

    # 构造3个主元的单位numpy数组
    print(np.eye(3, 3))
    '''[[1. 0. 0.]
     [0. 1. 0.]
     [0. 0. 1.]]'''
    

    empty():创建一个元素随机的数组

    # 构造一个4*4的随机numpy数组,里面的元素是随机生成的
    print(np.empty((4, 4)))
    '''[[6.23042070e-307 1.42417221e-306 7.56595733e-307 3.56043054e-307]
     [7.56595733e-307 1.00131040e-307 8.34426464e-308 6.23038336e-307]
     [1.42419394e-306 6.23059726e-307 1.06810268e-306 6.89809904e-307]
     [1.42420481e-306 1.24612013e-306 8.01091099e-307 9.34603679e-307]]'''
    

    reshape():重塑形状

    arr1 = np.zeros((1, 12))
    print(arr1.reshape((3, 4))) 
    '''[[0. 0. 0. 0.]
     [0. 0. 0. 0.]
     [0. 0. 0. 0.]]'''
    

    matplotlib模块

    定义:是一个绘图库,它可以创建常用的统计图,包括条形图,箱型图,折线图,散点图,饼图,直方图。

    条形图:

    from matplotlib import pyplot as plt #(潮流约定俗成的  当做plt)
    from matplotlib.font_manager import FontProperties #修改字体
    font = FontProperties(fname='C:WindowsFontssimsun.ttc') #字体的路径
    
    plt.style.use('ggplot') # 设置背景为条纹
    
    clas = ['3班','4班','5班','6班'] #x坐标的内容
    students = [50,55,45,60] #y坐标的内容
    clas_index = range(len(clas))#班级的索引
    
    
    plt.bar(clas_index,students,color='darkblue')#班级索引,学生人数,还有画布颜色
    
    plt.xlabel('学生',fontproperties=font)#中文打印出来会乱码,因为matplotlib是英文的,所以规定了字体
    plt.ylabel('学生人数',fontproperties=font)#中文打印出来会乱码,因为matplotlib是英文的,所以规定了字体
    plt.title('班级-学生人数',fontproperties=font,fontsize=20,fontweight=25)#顶部标题
    plt.xticks(clas_index,clas,fontproperties=font)#中文打印出来会乱码,因为matplotlib是英文的,所以规定了字体
    
    plt.show()#显示画布
    

    直方图:

    import numpy as np
    from matplotlib import pyplot as plt
    from matplotlib.font_manager import FontProperties
    font = FontProperties(fname='C:WindowsFontssimsun.ttc')
    
    plt.style.use('ggplot')
    
    x1 = np.random.rand(10000)
    
    x2 = np.random.rand(10000)
    
    fig = plt.figure()#生成一张画布
    ax1 = fig.add_subplot(1,2,1)#1行2列取第一个
    ax2 = fig.add_subplot(1,2,2)
    
    
    ax1.hist(x1,bins=50,color = 'darkblue')
    ax2.hist(x2,bins=50,color = 'y')
    
    
    fig.suptitle('两个正态分布',FontProperties=font,Fontsize = 20)
    ax1.set_title('x1的正态分布',FontProperties=font)#加子标题
    ax2.set_title('x2的正态分布',FontProperties=font)
    
    plt.show()
    

    折线图:

    import numpy as np
    from matplotlib import pyplot as plt
    from matplotlib.font_manager import FontProperties
    font = FontProperties(fname='C:WindowsFontssimsun.ttc')
    
    plt.style.use('ggplot')
    
    np.random.seed(10)#(x -- 10就相当于x变量)改变随机数生成器的种子seed。起到一个限制范围作用
    
    x1 = np.random.rand(40).cumsum()#cumsum()是计算数组各行的累加值
    x2 = np.random.rand(40).cumsum()
    x3 = np.random.rand(40).cumsum()
    x4 = np.random.rand(40).cumsum()
    
    plt.plot(x1,c='r',linestyle='-',marker='o',label ='红圆线')#marker就是折点的类型
    plt.plot(x2,c='y',linestyle='--',marker='*',label ='黄圆线')#linestyle就是折线的类型
    plt.plot(x3,c='b',linestyle='-.',marker='s',label ='蓝圆线')#c就是color的缩写表示颜色类型
    plt.plot(x4,c='black',linestyle=':',marker='s',label ='黑圆线')
    plt.legend(loc='best',prop = font)#显示折点(label)的类型在最佳位置就是左上角
    plt.show()
    

    散点图+直线图:

    import numpy as np
    from matplotlib import pyplot as plt
    from matplotlib.font_manager import FontProperties
    font = FontProperties(fname='C:WindowsFontssimsun.ttc')
    
    plt.style.use('ggplot')
    
    fig = plt.figure()#python中fig,ax=plt.subplots是python一种subplot可以画出很多子图
    ax1 = fig.add_subplot(1,2,1)#添加一个子图
    ax2 = fig.add_subplot(1,2,2)
    
    x = np.arange(20)
    y = x ** 2
    
    x2 = np.arange(20)
    y2 = x2
    
    ax1.scatter(x,y, c = 'r',label = '红')
    ax1.scatter(x2,y2, c = 'b',label = '蓝')
    
    ax2.plot(x,y)
    ax2.plot(x2,y2)
    
    fig.suptitle('两张图',FontProperties=font,fontsize=15)
    ax1.set_title('散点图',FontProperties=font)
    ax2.set_title('折线图',FontProperties=font)
    ax1.legend(prop = font)
    
    plt.show()
    

    pandas模块

    操作Excel/json/sql/ini/csv(配置文件)

    import numpy as np
    import pandas as pd
    
    np.random.seed(10)
    
    index = pd.date_range('2019-01-01', periods=6, freq='M')#periods周期   #freq频率
    # print(index)
    columns = ['c1', 'c2', 'c3', 'c4']#列头,相当于索引
    # print(columns)
    val = np.random.randn(6, 4)#6行4列
    # print(val)
    
    df = pd.DataFrame(index=index, columns=columns, data=val)#索引,列,数据(表格的内容)
    print(df)
    
    # 保存文件,读出成文件
    df.to_excel('date_c.xlsx')
    

    运行结果:

                      c1        c2        c3        c4
    2019-01-31  1.331587  0.715279 -1.545400 -0.008384
    2019-02-28  0.621336 -0.720086  0.265512  0.108549
    2019-03-31  0.004291 -0.174600  0.433026  1.203037
    2019-04-30 -0.965066  1.028274  0.228630  0.445138
    2019-05-31 -1.136602  0.135137  1.484537 -1.079805
    2019-06-30 -1.977728 -1.743372  0.266070  2.384967
    

    按照索引取值:

    print(df.loc['2019-01-31'])
    

    运行结果:

    c1    1.331587
    c2    0.715279
    c3   -1.545400
    c4   -0.008384
    Name: 2019-01-31 00:00:00, dtype: float64
    

    按索引取值,加上范围(这里加的是时间范围)

    print(df.loc['2019-01-31':'2019-05-31'])
    

    运行结果:

                      c1        c2        c3        c4
    2019-01-31  1.331587  0.715279 -1.545400 -0.008384
    2019-02-28  0.621336 -0.720086  0.265512  0.108549
    2019-03-31  0.004291 -0.174600  0.433026  1.203037
    2019-04-30 -0.965066  1.028274  0.228630  0.445138
    2019-05-31 -1.136602  0.135137  1.484537 -1.079805
    

    按照value取值:

    print(df)
    print(df.iloc[0, 0])#就是取第一个数值
    
    运行结果:
    1.331586504129518
    
    df.iloc[0, :] = 0#就是让第一行的值都为0
    print(df)
    

    运行结果:

                      c1        c2        c3        c4
    2019-01-31  0.000000  0.000000  0.000000  0.000000  #这一行就是取的值
    2019-02-28  0.621336 -0.720086  0.265512  0.108549
    2019-03-31  0.004291 -0.174600  0.433026  1.203037
    2019-04-30 -0.965066  1.028274  0.228630  0.445138
    2019-05-31 -1.136602  0.135137  1.484537 -1.079805
    2019-06-30 -1.977728 -1.743372  0.266070  2.384967
    
  • 相关阅读:
    Linux查看文件被哪个进程占用
    命令行启动rstudio server
    Spring Boot配置文件及多环境配置
    Spring Boot yml配置文件
    js实现自定义概率抽奖算法
    Flutter之adb: failed to install apk的解决方法
    Flutter之不简单的搜索条
    git操作之commit规范
    Flutter之毛玻璃效果的实现
    固定定位下div水平居中
  • 原文地址:https://www.cnblogs.com/gfhh/p/11609265.html
Copyright © 2011-2022 走看看