Python常用的模块和简单用法

张开发
2026/4/18 14:08:29 15 分钟阅读

分享文章

Python常用的模块和简单用法
1、random 随机模块import randomcode random.choice(stock_list)# 从一个列表中随机选取元素下面是我目前经常用到的模块为了方便使用不是有特殊需求的话个人觉得一开始没比亚每个模块都很深入学习只要知道自己常用的一些方法就行。随时更新请搜索使用。random 随机选取模块1234importrandoma[1,2,3,4,5]print(random.choice(a))# 随机从列表中抽取一个元素coderandom.choice(stock_list)# 从一个列表中随机选取元素os 文件夹模块1234567importos# 设置默认文件路径os.chdir()os.chdir(uC:/Users/Ocean/OneDrive/class5/data/input_data/stock_data)dfpd.read_csv(sz300001.csv)printdf程序根目录地址os.pardir父目录 parent directory12root_pathos.path.abspath(os.path.join(current_file, os.pardir, os.pardir))# 两级父目录printroot_path输入数据根目录地址1input_data_pathos.path.abspath(os.path.join(root_path,data,input_data))time 时间模块1importtime获取当前日期1date_nowtime.strftime(%Y-%m-%d, time.localtime(time.time()))计时器1234starttime.time()endtime.time()used_timestr(end-start)printused_time: used_time2、matplotlab.pyplot 作图模块1importmatplotlib.pyplot as plt添加空白画布1figplt.figure(figsize(12,5))在空白画布上设置一块区域1axfig.add_subplot(1,1,1)设置画块的标题123ax.set_title(str(code))ax.set_xlabel(Time)# 设置横坐标x轴的名字ax.set_ylabel(Return)# 设置Y轴画一根2D线图并设置名称为stock_return1plt.plot(df[equity], labelstock_return)绘制散点图1plt.scatter(df[ma_long], df[final_ratio], labelma_long)还有更多的图形可以绘制如果真的有需要可以网上再搜索12plt.legend(locbest)# 显示图线的名字plt.show()# 绘出图像结果3、mpl_toolkits.mplot3d 绘制3D图模块123456789frommpl_toolkits.mplot3dimportAxes3Dfigplt.figure()axAxes3D(fig)ax.scatter(df[ma_long],df[ma_short],df[final_ratio], cb)#绘制数据点# 设置坐标轴名字ax.set_zlabel(final_ratio)#坐标轴ax.set_ylabel(ma_short)ax.set_xlabel(ma_long)plt.show()

更多文章