zoukankan      html  css  js  c++  java
  • 【python】numpy库和matplotlib库学习笔记

    Numpy库

    numpy:科学计算包,支持N维数组运算、处理大型矩阵、成熟的广播函数库、矢量运算、线性代数、傅里叶变换、随机数生成,并可与C++/Fortran语言无缝结合。树莓派Python v3默认安装已经包含了numpy。

    ①    导入模块

    >>> import numpy as np

    ②    生成数组

    >>> np.array([1, 2, 3, 4, 5])        # 把列表转换为数组

    array([1, 2, 3, 4, 5])

    >>> np.array((1, 2, 3, 4, 5))        # 把元组转换成数组

    array([1, 2, 3, 4, 5])

    >>> np.array(range(5))             # 把range对象转换成数组

    array([0, 1, 2, 3, 4])

    >>> np.array([[1, 2, 3], [4, 5, 6]])      # 二维数组

    array([[1, 2, 3],

           [4, 5, 6]])

    >>> np.arange(8)                     # 类似于内置函数range()

    array([0, 1, 2, 3, 4, 5, 6, 7])

    >>> np.arange(1, 10, 2)

    array([1, 3, 5, 7, 9])

    >>> np.linspace(0, 10, 11)         # 等差数组,包含11个数

    array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

    >>> np.linspace(0, 10, 11, endpoint=False) # 不包含终点

    array([ 0.        ,  0.90909091,  1.81818182,  2.72727273,  3.63636364,

            4.54545455,  5.45454545,  6.36363636,  7.27272727,  8.18181818,

            9.09090909])

    >>> np.logspace(0, 100, 10)        # 对数数组

    array([ 1.00000000e+000,   1.29154967e+011,   1.66810054e+022,

            2.15443469e+033,   2.78255940e+044,   3.59381366e+055,

            4.64158883e+066,   5.99484250e+077,   7.74263683e+088,

            1.00000000e+100])

    >>> np.logspace(1,6,5, base=2)     # 对数数组,相当于2 ** np.linspace(1,6,5)

    array([  2.        ,   4.75682846,  11.3137085 ,  26.90868529,  64.        ])

    >>> np.zeros(3)                    # 全0一维数组

    array([ 0.,  0.,  0.])

    >>> np.ones(3)                     # 全1一维数组

    array([ 1.,  1.,  1.])

    >>> np.zeros((3,3))              # 全0二维数组,3行3列

    [[ 0.  0.  0.]

     [ 0.  0.  0.]

     [ 0.  0.  0.]]

    >>> np.zeros((3,1))              # 全0二维数组,3行1列

    array([[ 0.],

           [ 0.],

           [ 0.]])

    >>> np.zeros((1,3))              # 全0二维数组,1行3列

    array([[ 0.,  0.,  0.]])

    >>> np.ones((1,3))               # 全1二维数组

    array([[ 1.,  1.,  1.]])

    >>> np.ones((3,3))               # 全1二维数组

    array([[ 1.,  1.,  1.],

           [ 1.,  1.,  1.],

           [ 1.,  1.,  1.]])

    >>> np.identity(3)      # 单位矩阵

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

           [ 0.,  1.,  0.],

           [ 0.,  0.,  1.]])

    >>> np.identity(2)

    array([[ 1.,  0.],

           [ 0.,  1.]])

    >>> np.empty((3,3))     # 空数组,只申请空间而不初始化,元素值是不确定的

    array([[ 0.,  0.,  0.],

           [ 0.,  0.,  0.],

           [ 0.,  0.,  0.]])

    数组与数值的运算

    >>> x = np.array((1, 2, 3, 4, 5))    # 创建数组对象

    >>> x

    array([1, 2, 3, 4, 5])

    >>> x * 2                            # 数组与数值相乘,返回新数组

    array([ 2, 4, 6, 8, 10])

    >>> x / 2                            # 数组与数值相除

    array([ 0.5, 1. , 1.5, 2. , 2.5])

    >>> x // 2                           # 数组与数值整除

    array([0, 1, 1, 2, 2], dtype=int32)

    >>> x ** 3                           # 幂运算

    array([1, 8, 27, 64, 125], dtype=int32)

    >>> x + 2                            # 数组与数值相加

    array([3, 4, 5, 6, 7])

    >>> x % 3                            # 余数

    array([1, 2, 0, 1, 2], dtype=int32)

    >>> 2 ** x

    array([2, 4, 8, 16, 32], dtype=int32)

    >>> 2 / x

    array([2. ,1. ,0.66666667, 0.5, 0.4])

    >>> 63 // x

    array([63, 31, 21, 15, 12], dtype=int32)

    数组与数组的运算

    >>> a = np.array((1, 2, 3))

    >>> b = np.array(([1, 2, 3], [4, 5, 6], [7, 8, 9]))

    >>> c = a * b                   # 数组与数组相乘

    >>> c                           # a中的每个元素乘以b中的对应列元素

    array([[ 1, 4, 9],

           [ 4, 10, 18],

           [ 7, 16, 27]])

    >>> c / b                       # 数组之间的除法运算

    array([[ 1.,  2.,  3.],

           [ 1.,  2.,  3.],

           [ 1.,  2.,  3.]])

    >>> c / a

    array([[ 1.,  2.,  3.],

           [ 4.,  5.,  6.],

          [ 7.,  8.,  9.]])

    >>> a + a                         # 数组之间的加法运算

    array([2, 4, 6])

    >>> a * a                         # 数组之间的乘法运算

    array([1, 4, 9])

    >>> a - a                         # 数组之间的减法运算

    array([0, 0, 0])

    >>> a / a                         # 数组之间的除法运算

    array([ 1.,  1.,  1.])

    转置

    >>> b = np.array(([1, 2, 3], [4, 5, 6], [7, 8, 9]))

    >>> b

    array([[1, 2, 3],

           [4, 5, 6],

           [7, 8, 9]])

    >>> b.T                           # 转置

    array([[1, 4, 7],

           [2, 5, 8],

           [3, 6, 9]])

    >>> a = np.array((1, 2, 3, 4))

    >>> a

    array([1, 2, 3, 4])

    >>> a.T                           # 一维数组转置以后和原来是一样的

    array([1, 2, 3, 4])

    点积/内积

    >>> a = np.array((5, 6, 7))

    >>> b = np.array((6, 6, 6))

    >>> a.dot(b)                                # 向量内积

    108

    >>> np.dot(a,b)

    108

    >>> c = np.array(([1,2,3],[4,5,6],[7,8,9])) # 二维数组

    >>> c.dot(a)                              # 二维数组的每行与一维向量计算内积

    array([ 38, 92, 146])

    >>> a.dot(c)                # 一维向量与二维向量的每列计算内积

    array([78, 96, 114])

    数组元素访问

    >>> b = np.array(([1,2,3],[4,5,6],[7,8,9]))

    >>> b

    array([[1, 2, 3],

           [4, 5, 6],

           [7, 8, 9]])

    >>> b[0]              # 第0行

    array([1, 2, 3])

    >>> b[0][0]           # 第0行第0列的元素值

    1

    >>> b[0,2]            # 第0行第2列的元素值

    3

    >>> b[[0,1]]          # 第0行和第1行

    array([[1, 2, 3],

           [4, 5, 6]])

    >>> b[[0,1], [1,2]]   #第0行第1列的元素和第1行第2列的元素

    array([2, 6])

    >>> x = np.arange(0,100,10,dtype=np.floating)

    >>> x

    array([  0.,  10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90.])

    >>> x[[1, 3, 5]]                 # 同时访问多个位置上的元素

    array([ 10.,  30.,  50.])

    >>> x[[1, 3, 5]] = 3             # 把多个位置上的元素改为相同的值

    >>> x

    array([  0.,   3.,  20.,   3.,  40.,   3.,  60.,  70.,  80.,  90.])

    >>> x[[1, 3, 5]] = [34, 45, 56]  # 把多个位置上的元素改为不同的值

    >>> x

    array([  0.,  34.,  20.,  45.,  40.,  56.,  60.,  70.,  80.,  90.])

    数组支持函数运算

     >>> x = np.arange(0, 100, 10, dtype=np.floating)

    >>> np.sin(x)                             # 一维数组中所有元素求正弦值

    array([ 0.        , -0.54402111,  0.91294525, -0.98803162,  0.74511316,

          -0.26237485, -0.30481062,  0.77389068, -0.99388865,  0.89399666])

    >>> b = np.array(([1, 2, 3], [4, 5, 6], [7, 8, 9]))

    >>> np.cos(b)                             # 二维数组中所有元素求余弦值

    array([[ 0.54030231, -0.41614684, -0.9899925 ],

           [-0.65364362,  0.28366219,  0.96017029],

           [ 0.75390225, -0.14550003, -0.91113026]])

    >>> np.round(_)                           # 四舍五入

    array([[ 1., -0., -1.],

           [-1.,  0.,  1.],

           [ 1., -0., -1.]])

    >>> x = np.random.rand(10) * 10            # 包含10个随机数的数组

    >>> x

    array([ 2.16124573,  2.58272611,  6.18827437,  5.21282916,  4.06596404,

            3.34858432,  5.60654631,  9.49699461,  1.68564166,  2.9930861 ])

    >>> np.floor(x)                            # 所有元素向下取整

    array([ 2.,  2.,  6.,  5.,  4.,  3.,  5.,  9.,  1.,  2.])

    >>> np.ceil(x)                             # 所有元素向上取整

    array([  3.,   3.,   7.,   6.,   5.,   4.,   6.,  10.,   2.,   3.])

    改变数组大小

     >>> a = np.arange(1, 11, 1)

    >>> a

    array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

    >>> a.shape = 2, 5                         # 改为2行5列

    >>> a

    array([[ 1,  2,  3,  4,  5],

           [ 6,  7,  8,  9, 10]])

    >>> a.shape = 5, -1                        # -1表示自动计算,原地修改

    >>> a

    array([[ 1,  2],

           [ 3,  4],

           [ 5,  6],

           [ 7,  8],

           [ 9, 10]])

    >>> b = a.reshape(2,5)                     # reshape()方法返回新数组

    >>> b

    array([[ 1,  2,  3,  4,  5],

           [ 6,  7,  8,  9, 10]])

     切片操作

     >>> a = np.arange(10)

    >>> a

    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

    >>> a[::-1]                           # 反向切片

    array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

    >>> a[::2]                            # 隔一个取一个元素

    array([0, 2, 4, 6, 8])

    >>> a[:5]                             # 前5个元素

    array([0, 1, 2, 3, 4])

    >>> c = np.arange(25)     # 创建数组

    >>> c.shape = 5,5         # 修改数组大小

    >>> c

    array([[ 0,  1,  2,  3,  4],

           [ 5,  6,  7,  8,  9],

           [10, 11, 12, 13, 14],

           [15, 16, 17, 18, 19],

           [20, 21, 22, 23, 24]])

    >>> c[0, 2:5]             # 第0行中下标[2,5)之间的元素值

    array([2, 3, 4])

    >>> c[1]                  # 第0行所有元素

    array([5, 6, 7, 8, 9])

    >>> c[2:5, 2:5]           # 行下标和列下标都介于[2,5)之间的元素值

    array([[12, 13, 14],

           [17, 18, 19],

           [22, 23, 24]])

    11、布尔运算

    >>> x = np.random.rand(10) # 包含10个随机数的数组

    >>> x

    array([ 0.56707504,  0.07527513,  0.0149213 ,  0.49157657,  0.75404095,

          0.40330683,  0.90158037,  0.36465894,  0.37620859,  0.62250594])

    >>> x > 0.5               # 比较数组中每个元素值是否大于0.5

    array([ True, False, False, False,  True, False,  True, False, False,  True], dtype=bool)

    >>> x[x>0.5]              # 获取数组中大于0.5的元素,可用于检测和过滤异常值

    array([ 0.56707504,  0.75404095,  0.90158037,  0.62250594])

    12、广播

     >>> a = np.arange(0,60,10).reshape(-1,1)     # 列向量

    >>> b = np.arange(0,6)                       # 行向量

    >>> a

    array([[ 0],

           [10],

           [20],

           [30],

           [40],

           [50]])

    >>> b

    array([0, 1, 2, 3, 4, 5])

    >>> a[0] + b                                 # 数组与标量的加法

    array([0, 1, 2, 3, 4, 5])

    13、计算唯一值以及出现次数

     >>> x = np.random.randint(0, 10, 7)

    >>> x

    array([8, 7, 7, 5, 3, 8, 0])

    >>> np.bincount(x)   # 元素出现次数,0出现1次,

                         # 1、2没出现,3出现1次,以此类推

    array([1, 0, 0, 1, 0, 1, 0, 2, 2], dtype=int64)

    >>> np.sum(_)        # 所有元素出现次数之和等于数组长度

    7

    >>> np.unique(x)     # 返回唯一元素值

    array([0, 3, 5, 7, 8])

    14、矩阵运算

     >>> a_list = [3, 5, 7]

    >>> a_mat = np.matrix(a_list)            # 创建矩阵

    >>> a_mat

    matrix([[3, 5, 7]])

    >>> a_mat.T                              # 矩阵转置

    matrix([[3],

            [5],

            [7]])

    >>> a_mat.shape                          # 矩阵形状

    (1, 3)

    >>> a_mat.size 

    3                         # 元素个数

    >>> a_mat.mean()                         # 元素平均值

    5.0

    >>> a_mat.sum()                          # 所有元素之和

    15

    >>> a_mat.max()                          # 最大值

    7

    >>> a_mat.max(axis=1)                    # 横向最大值

    matrix([[7]])

    >>> a_mat.max(axis=0)                    # 纵向最大值

    matrix([[3, 5, 7]])

    >>> b_mat = np.matrix((1, 2, 3))         # 创建矩阵

    >>> b_mat

    matrix([[1, 2, 3]])

    >>> a_mat * b_mat.T                      # 矩阵相乘

    matrix([[34]])

     

    Matplotlib学习笔记

    matplotlib模块依赖于numpy模块和tkinter模块,可以绘制多种形式的图形,包括线图、直方图、饼状图、散点图、误差线图等等,图形质量可满足出版要求,是数据可视化的重要工具。

    ①  绘制正弦曲线

     1 import numpy as np
     2 
     3 import pylab as pl
     4 
     5 t = np.arange(0.0, 2.0*np.pi, 0.01)  #生成数组,0到2π之间,以0.01为步长
     6 
     7 s = np.sin(t)                        #对数组中所有元素求正弦值,得到新数组
     8 
     9 pl.plot(t,s)                         #画图,以t为横坐标,s为纵坐标
    10 
    11 pl.xlabel('x')                       #设置坐标轴标签
    12 
    13 pl.ylabel('y')
    14 
    15 pl.title('sin')                                    #设置图形标题
    16 
    17 pl.show()                                          #显示图形

    ②    绘制散点图

    >>> a = np.arange(0, 2.0*np.pi, 0.1)

    >>> b = np.cos(a)

    >>> pl.scatter(a,b)

    >>> pl.show()

     1 import matplotlib.pylab as pl
     2 
     3 import numpy as np
     4 
     5 x = np.random.random(100)
     6 
     7 y = np.random.random(100)  #s指大小,c指颜色,marker指符号形状
     8 pl.scatter(x,y,s=x*500,c=u'r',marker=u'*')
     9 pl.show()

    ③    绘制饼状图

     1 import numpy as np
     2 
     3 import matplotlib.pyplot as plt
     4 
     5 labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
     6 
     7 colors = ['yellowgreen', 'gold', '#FF0000', 'lightcoral']
     8 
     9 explode = (0, 0.1, 0, 0.1)              # 使饼状图中第2片和第4片裂开
    10 
    11 fig = plt.figure()
    12 
    13 ax = fig.gca()
    14 
    15 ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
    16 
    17        autopct='%1.1f%%', shadow=True, startangle=90,
    18 
    19        radius=0.25, center=(0, 0), frame=True)   # autopct设置饼内百分比的格式
    20 
    21 ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
    22 
    23        autopct='%1.1f%%', shadow=True, startangle=45,
    24 
    25        radius=0.25, center=(1, 1), frame=True)
    26 
    27 ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
    28 
    29        autopct='%1.1f%%', shadow=True, startangle=90,
    30 
    31        radius=0.25, center=(0, 1), frame=True)
    32 
    33 ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
    34 
    35        autopct='%1.2f%%', shadow=False, startangle=135,
    36 
    37        radius=0.35, center=(1, 0), frame=True)
    38 
    39 ax.set_xticks([0, 1])                    # 设置坐标轴刻度
    40 
    41 ax.set_yticks([0, 1])
    42 
    43 ax.set_xticklabels(["Sunny", "Cloudy"])  # 设置坐标轴刻度上的标签
    44 
    45 ax.set_yticklabels(["Dry", "Rainy"])
    46 
    47 ax.set_xlim((-0.5, 1.5))                 # 设置坐标轴跨度
    48 
    49 ax.set_ylim((-0.5, 1.5))
    50 
    51 ax.set_aspect('equal')                   # 设置纵横比相等
    52 
    53 plt.show()

    ④    绘制带有中文标签和图例的图

     1 import numpy as np
     2 
     3 import pylab as pl
     4 
     5 import matplotlib.font_manager as fm
     6 
     7 myfont = fm.FontProperties(fname=r'C:WindowsFontsSTKAITI.ttf') #设置字体
     8 
     9 t = np.arange(0.0, 2.0*np.pi, 0.01)                       # 自变量取值范围
    10 
    11 s = np.sin(t)                                             # 计算正弦函数值
    12 
    13 z = np.cos(t)                                             # 计算余弦函数值
    14 
    15 pl.plot(t, s, label='正弦')
    16 
    17 pl.plot(t, z, label='余弦')
    18 
    19 pl.xlabel('x-变量', fontproperties='STKAITI', fontsize=18) # 设置x标签
    20 
    21 pl.ylabel('y-正弦余弦函数值', fontproperties='simhei', fontsize=18)
    22 
    23 pl.title('sin-cos函数图像', fontproperties='STLITI', fontsize=24)
    24 
    25 pl.legend(prop=myfont)                                                          # 设置图例
    26 
    27 pl.show()

    ⑥  绘制三维图形

     1 import pylab as pl
     2 
     3 import numpy as np
     4 
     5 import mpl_toolkits.mplot3d
     6 
     7 rho, theta = np.mgrid[0:1:40j, 0:2*np.pi:40j]
     8 
     9 z = rho**2
    10 
    11 x = rho*np.cos(theta)
    12 
    13 y = rho*np.sin(theta)
    14 
    15 ax = pl.subplot(111, projection='3d')
    16 
    17 ax.plot_surface(x,y,z)
    18 
    19 pl.show()

     

  • 相关阅读:
    java第二周的学习知识
    java第一次课
    今天晚上有事,代码假期完成。
    [leetcode] Minimum Path Sum
    java访问权限整理
    java IO整理-File
    java初始化顺序
    enum使用整理
    工厂模式总结
    java IO-流
  • 原文地址:https://www.cnblogs.com/litchi666/p/12836936.html
Copyright © 2011-2022 走看看