esai大树聚吧 关注:13贴子:345
  • 6回复贴,共1

python 基础功能

只看楼主收藏回复

np.random.rand() # 没有参数则直接⽣成⼀个[0,1)区间的随机数
0.1065982531337718
>>> np.random.rand(3) # 只有⼀个参数则⽣成n*1个随机数
array([0.24640203, 0.81910232, 0.79941588])
>>> np.random.rand(2, 3, 4) # 有多个参数,则⽣成对应形状随机数,如本例⽣成shape为2*3*4的随机数

np.random.uniform(2,7,(4,5))#⽣成2到7之间的随机数,维度4⾏5列

np.random.randint(10,29,(3,7))#产生10到29之间的3行7列整数矩阵
array([[25,10,20,25,21,26,26],
[10,11,16,28,12,20,26],.....
-------------------------------------------------------------------
产⽣随机数
rand(d0, d1, …, dn) Random values in a given shape.
randn(d0, d1, …, dn) Return a sample (or samples) from the “standard normal” distribution.
randint(low[, high, size, dtype]) Return random integers from low (inclusive) to high (exclusive).
random_integers(low[, high, size]) Random integers of type np.int between low and high, inclusive.
random_sample([size]) Return random floats in the half-open interval [0.0, 1.0).
random([size]) Return random floats in the half-open interval [0.0, 1.0).
ranf([size]) Return random floats in the half-open interval [0.0, 1.0).
sample([size]) Return random floats in the half-open interval [0.0, 1.0).
choice(a[, size, replace, p]) Generates a random sample from a given 1-D array
bytes(length) Return random bytes.
打乱随机数
shuffle(x) Modify a sequence in-place by shuffling its contents.
permutation(x) Randomly permute a sequence, or return a permuted range
--------------------------------------------------------
作者:天神太院明骞骞010
链接:https://wenku.baidu.com/view/01418630084e767f5acfa1c7aa00b52acfc79c62.html


IP属地:湖南1楼2022-05-11 16:16回复
    import matplotlib.pyplot as plt
    import numpy as np
    list1=[1,2,3,4,5,6,2,3,4,6,7,5,7]
    list2=[2,3,4,5,8,9,2,1,3,4,5,2,4]
    plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
    plt.title('显示中文标题')
    plt.xlabel("横坐标")
    plt.ylabel("纵坐标")
    x=np.arange(0,len(list1))+1
    x[0]=1
    my_x_ticks = np.arange(1, 14, 1)
    plt.xticks(my_x_ticks)
    plt.plot(x,list1,label='list1',marker = "o",markersize=10)#marker设置标记形状 markersize设置标记大小
    plt.plot(x,list2,label='list2',marker = "x",markersize=8)
    plt.legend()
    plt.grid()#添加网格
    plt.show()

    https://blog.csdn.net/q6q6q/article/details/109341451
    具体来说是pylab和pyplot这两个子库。这两个库可以满足基本的画图需求,而条形图,散点图等特殊图,下面再单独具体介绍。
    首先给出pylab神器镇文:pylab.rcParams.update(params)。这个函数几乎可以调节图的一切属性,包括但不限于:坐标范围,axes标签字号大小,xtick,ytick标签字号,图线宽,legend字号等。
    import matplotlib.pyplot as plt
    import matplotlib.pylab as pylab
    import scipy.io
    import numpy as np
    params={
    'axes.labelsize': '35',
    'xtick.labelsize':'27',
    'ytick.labelsize':'27',
    'lines.linewidth':2 ,
    'legend.fontsize': '27',
    'figure.figsize' : '12, 9' # set figure size
    }
    pylab.rcParams.update(params) #set figure parameter
    #line_styles=['ro-','b^-','gs-','ro--','b^--','gs--'] #set line style
    #We give the coordinate date directly to give an example.
    x1 = [-20,-15,-10,-5,0,0,5,10,15,20]
    y1 = [0,0.04,0.1,0.21,0.39,0.74,0.78,0.80,0.82,0.85]
    y2 = [0,0.014,0.03,0.16,0.37,0.78,0.81,0.83,0.86,0.92]
    y3 = [0,0.001,0.02,0.14,0.34,0.77,0.82,0.85,0.90,0.96]
    y4 = [0,0,0.02,0.12,0.32,0.77,0.83,0.87,0.93,0.98]
    y5 = [0,0,0.02,0.11,0.32,0.77,0.82,0.90,0.95,1]
    plt.plot(x1,y1,'bo-',label='m=2, p=10%',markersize=20) # in 'bo-', b is blue, o is O marker, - is solid line and so on
    plt.plot(x1,y2,'gv-',label='m=4, p=10%',markersize=20)
    plt.plot(x1,y3,'ys-',label='m=6, p=10%',markersize=20)
    plt.plot(x1,y4,'ch-',label='m=8, p=10%',markersize=20)
    plt.plot(x1,y5,'mD-',label='m=10, p=10%',markersize=20)
    fig1 = plt.figure(1)
    axes = plt.subplot(111)
    #axes = plt.gca()
    axes.set_yticks([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])
    axes.grid(True) # add grid
    plt.legend(loc="lower right") #set legend location
    plt.ylabel('Percentage') # set ystick label
    plt.xlabel('Difference') # set xstck label
    plt.savefig('D:\commonNeighbors_CDF_snapshots.eps',dpi = 1000,bbox_inches='tight')
    plt.show()
    显示效果如下:
    plt.subplot(111)和plt.subplot(1,1,1)是等价的。意思是将区域分成1行1列,当前画的是第一个图(排序由行至列)。
    plt.subplot(211)意思就是将区域分成2行1列,当前画的是第一个图(第一行,第一列)。以此类推,只要不超过10,逗号就可省去。
    python画条形图。代码如下。
    import scipy.io
    import numpy as np
    import matplotlib.pylab as pylab
    import matplotlib.pyplot as plt
    import matplotlib.ticker as mtick
    params={
    'axes.labelsize': '35',
    'xtick.labelsize':'27',
    'ytick.labelsize':'27',
    'lines.linewidth':2 ,
    'legend.fontsize': '27',
    'figure.figsize' : '24, 9'
    }
    pylab.rcParams.update(params)
    y1 = [9.79,7.25,7.24,4.78,4.20]
    y2 = [5.88,4.55,4.25,3.78,3.92]
    y3 = [4.69,4.04,3.84,3.85,4.0]
    y4 = [4.45,3.96,3.82,3.80,3.79]
    y5 = [3.82,3.89,3.89,3.78,3.77]
    ind = np.arange(5) # the x locations for the groups
    width = 0.15
    plt.bar(ind,y1,width,color = 'blue',label = 'm=2')
    plt.bar(ind+width,y2,width,color = 'g',label = 'm=4') # ind+width adjusts the left start location of the bar.
    plt.bar(ind+2*width,y3,width,color = 'c',label = 'm=6')
    plt.bar(ind+3*width,y4,width,color = 'r',label = 'm=8')
    plt.bar(ind+4*width,y5,width,color = 'm',label = 'm=10')
    plt.xticks(np.arange(5) + 2.5*width, ('10%','15%','20%','25%','30%'))
    plt.xlabel('Sample percentage')
    plt.ylabel('Error rate')
    fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
    xticks = mtick.FormatStrFormatter(fmt)
    # Set the formatter
    axes = plt.gca() # get current axes
    axes.yaxis.set_major_formatter(xticks) # set % format to ystick.
    axes.grid(True)
    plt.legend(loc="upper right")
    plt.savefig('D:\errorRate.eps', format='eps',dpi = 1000,bbox_inches='tight')
    plt.show()
    结果如下:
    画散点图,主要是scatter这个函数,其他类似。
    画网络图,要用到networkx这个库,下面给出一个实例:
    import networkx as nx
    import pylab as plt
    g = nx.Graph()
    g.add_edge(1,2,weight = 4)
    g.add_edge(1,3,weight = 7)
    g.add_edge(1,4,weight = 8)
    g.add_edge(1,5,weight = 3)
    g.add_edge(1,9,weight = 3)
    g.add_edge(1,6,weight = 6)
    g.add_edge(6,7,weight = 7)
    g.add_edge(6,8,weight = 7)
    g.add_edge(6,9,weight = 6)
    g.add_edge(9,10,weight = 7)
    g.add_edge(9,11,weight = 6)
    fixed_pos = {1:(1,1),2:(0.7,2.2),3:(0,1.8),4:(1.6,2.3),5:(2,0.8),6:(-0.6,-0.6),7:(-1.3,0.8), 8:(-1.5,-1), 9:(0.5,-1.5), 10:(1.7,-0.8), 11:(1.5,-2.3)} #set fixed layout location
    #pos=nx.spring_layout(g) # or you can use other layout set in the module
    nx.draw_networkx_nodes(g,pos = fixed_pos,nodelist=[1,2,3,4,5],
    node_color = 'g',node_size = 600)
    nx.draw_networkx_edges(g,pos = fixed_pos,edgelist=[(1,2),(1,3),(1,4),(1,5),(1,9)],edge_color='g',width = [4.0,4.0,4.0,4.0,4.0],label = [1,2,3,4,5],node_size = 600)
    nx.draw_networkx_nodes(g,pos = fixed_pos,nodelist=[6,7,8],
    node_color = 'r',node_size = 600)
    nx.draw_networkx_edges(g,pos = fixed_pos,edgelist=[(6,7),(6,8),(1,6)],width = [4.0,4.0,4.0],edge_color='r',node_size = 600)
    nx.draw_networkx_nodes(g,pos = fixed_pos,nodelist=[9,10,11],
    node_color = 'b',node_size = 600)
    nx.draw_networkx_edges(g,pos = fixed_pos,edgelist=[(6,9),(9,10),(9,11)],width = [4.0,4.0,4.0],edge_color='b',node_size = 600)
    plt.text(fixed_pos[1][0],fixed_pos[1][1]+0.2, s = '1',fontsize = 40)
    plt.text(fixed_pos[2][0],fixed_pos[2][1]+0.2, s = '2',fontsize = 40)
    plt.text(fixed_pos[3][0],fixed_pos[3][1]+0.2, s = '3',fontsize = 40)
    plt.text(fixed_pos[4][0],fixed_pos[4][1]+0.2, s = '4',fontsize = 40)
    plt.text(fixed_pos[5][0],fixed_pos[5][1]+0.2, s = '5',fontsize = 40)
    plt.text(fixed_pos[6][0],fixed_pos[6][1]+0.2, s = '6',fontsize = 40)
    plt.text(fixed_pos[7][0],fixed_pos[7][1]+0.2, s = '7',fontsize = 40)
    plt.text(fixed_pos[8][0],fixed_pos[8][1]+0.2, s = '8',fontsize = 40)


    IP属地:湖南2楼2022-05-11 16:28
    回复
      2026-01-26 21:02:05
      广告
      不感兴趣
      开通SVIP免广告
      第一步:让Python引入turtle模块,引入模块就是告诉Python你想要用它。
      importturtle
      第二步:创建画布。调用turtle中的Pen函数。
      t=turtle.Pen()
      第三步:移动海龟。
      t.forward(50)
      forward的中文意思是“向前地;促进”。所以这行代码的意思是海龟向前移动50个像素:
      t.left(90)
      让海龟左转90度

      现在我们可以尝试画一个方块,思路就是前进-转向90度-前进,循环四次。
      123456789 >>> t.forward(50)>>> t.left(90)>>> t.forward(50)>>> t.left(90)>>> t.forward(50)>>> t.left(90)>>> t,forward(50)>>> t.left(90)>>> t,forward(50)
      第四步:擦除画布。
      >>>t.reset()
      重置命令(reset)这会清除画布并把海龟放回开始的位置。
      >>>t.clear()
      清除命令(clear)只清除屏幕,海龟仍停留在原位。
      我们还可以让海龟向右(right)转,或者让它后退(backward)。我们可以用向上(up)来把笔从纸上抬起来(换句话说就是让海龟停止作画),用向下(down)来开始作画。
      综合运用一下,画两条线。
      12345678 >>> t.reset() //擦除画布并把海龟移回到开始位置>>> t.backward(100) //后退100个像素>>> t.up() // 抬笔不再作画>>> t.right(90) //向右转90度>>> t.forward(20) //前进20个像素>>> t.left(90) //向左转90度>>> t.down() //下笔准备作画>>> t.forward(100) //前进100个像素

      Python画三角形代码如下:
      from turtle import*  #从turtle中导出所有模块
      seth(0)    #设置角度为0°
      fd(200)    #forward,向前200像素,即边长为200像素
      seth(120)   #设置角度120°
      fd(200)    #向前200像素,即边长为200像素
      seth(240)   #设置角度240°
      fd(200)    #向前200像素,即边长为200像素
      done()    #结束,暂停
      turtle是一个简单的绘图工具。它提供了一个海龟,你可以把它理解为一个机器人,只听得懂有限的指令。
      1.在文件头写上如下行,这能让我们在语句中插入中文
      #-*-coding:utf-8-*-
      2.用importturtle导入turtle库
      3.绘图窗口的原点(0,0)在正中间。默认情况下,海龟向正右方移动。
      4.操纵海龟绘图有着许多的命令,这些命令可以划分为两种:一种为运动命令,一种为画笔控制命令
      (1)运动命令:
      forward(d) 向前移动距离d代表距离
      backward(d) 向后移动距离d代表距离
      right(degree) 向右转动多少度
      left(degree) 向左转动多少度
      goto(x,y) 将画笔移动到坐标为(x,y)的位置
      stamp() 绘制当前图形
      speed(speed) 画笔绘制的速度范围[0,10]整数
      (2)画笔控制命令:
      down() 画笔落下,移动时绘制图形
      up() 画笔抬起,移动时不绘制图形
      setheading(degree) 海龟朝向,degree代表角度
      reset() 恢复所有设置
      pensize(width) 画笔的宽度
      pencolor(colorstring) 画笔的颜色
      fillcolor(colorstring) 绘制图形的填充颜色
      fill(Ture)
      fill(False)
      circle(radius, extent) 绘制一个圆形,其中radius为半径,extent为度数,例如若extent为180,则画一个半圆;如要画一个圆形,可不必写第二个参数


      IP属地:湖南3楼2022-05-11 16:35
      回复
        python 导入数据文件:
        import numpy as np
        import pandas as pd
        df=pd.read_csv('train.csv')
        报错时,尝试使⽤os.getcwd()查看当前⼯作⽬录。

        获取帮助:
        Python内置函数
        help(pd.read_csv)

        使用 Pandas 读取Flat文件
        filename = 'demo.csv' data = pd.read_csv(filename, nrows=5, # 要读取的文件的行数 header=None, # 作为列名的行号 sep='\t', # 分隔符使用 comment='#', # 分隔注释的字符 na_values=[""]) # 可以识别为NA/NaN的字符串
        Pandas中的ExcelFile()是pandas中对excel表格文件进行读取相关操作非常方便快捷的类,尤其是在对含有多个sheet的excel文件进行操控时非常方便。
        file = 'demo.xlsx' data = pd.ExcelFile(file) df_sheet2 = data.parse(sheet_name='1960-1966', skiprows=[0], names=['Country', 'AAM: War(2002)']) df_sheet1 = pd.read_excel(data, sheet_name=0, parse_cols=[0], skiprows=[0], names=['Country'])
        使用sheet_names属性获取要读取工作表的名称。
        data.sheet_names
        关系型数据库
        from sqlalchemy import create_engine engine = create_engine('sqlite://Northwind.sqlite')
        使用table_names()方法获取一个表名列表
        table_names = engine.table_names()
        1、直接查询关系型数据库
        con = engine.connect() rs = con.execute("SELECT * FROM Orders") df = pd.DataFrame(rs.fetchall()) df.columns = rs.keys() con.close()
        使用上下文管理器 -- with
        with engine.connect() as con: rs = con.execute("SELECT OrderID FROM Orders") df = pd.DataFrame(rs.fetchmany(size=5)) df.columns = rs.keys()
        2、使用Pandas查询关系型数据库
        df = pd.read_sql_query("SELECT * FROM Orders", engine)

        数据探索
        数据导入后会对数据进行初步探索,如查看数据类型,数据大小、长度等一些基本信息。这里简单总结一些。
        1、NumPy Arrays
        data_array.dtype # 数组元素的数据类型
        data_array.shape # 阵列尺寸
        len(data_array) # 数组的长度
        2、Pandas DataFrames
        df.head() # 返回DataFrames前几行(默认5行)
        df.tail() # 返回DataFrames最后几行(默认5行)
        df.index # 返回DataFrames索引
        df.columns # 返回DataFrames列名 http://
        df.info() # 返回DataFrames基本信息
        data_array = data.values # 将DataFrames转换为NumPy数组


        IP属地:湖南4楼2022-05-11 16:50
        回复
          module 'matplotlib' has no attribute 'pyplot'
          原因在于第一次调入时,杀毒软件把某个东西杀死了
          重新安装一次看看

          Python 第三方包都会在指定网站 https://pypi.org/ 上发布
          清华大学开源软件镜像站的 PyPI 地址是:https://mirrors.tuna.tsinghua.edu.cn/help/pypi

          1. 卸载包matplotlib
          2.pip uninstall requests
          会提示是否需要卸载此模块,输入 y 则卸载。如果确定无疑要卸载,还可以用:
          % pip uninstall requests -y
          3.安装方法,可以用 pip install requests (顶部所示),
          也可以用 python -m pip install requests (截图底部所示)
          或者:安装老版本
          pip install requests == 2.25.0
          4.查看:
          pip list
          pip show pandas
          5.升级:pip install --upgrade requests


          IP属地:湖南5楼2022-05-11 20:23
          收起回复
            Installing collected packages: matplotlib
            ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310-32\\Lib\\site-packages\\matplotlib\\_image.cp310-win32.pyd'
            Consider using the `--user` option or check the permissions.
            C:\Users\Administrator>pip install matplotlib --user
            加了参数--user,
            安装成功!


            IP属地:湖南6楼2022-05-11 20:27
            回复