实验4.1:NumPy数据分析
题目描述:利用NumPy库完成2项编程任务。实验效果如图1-1所示。 (1)创建一个一维数组arr1,存放10个[10, 99]随机整数,计算其最大值,最小值和平均值。 (2)创建一个二维数组arr2,存放5行5列共25个[10, 99]随机整数,计算其最大值,最小值和平均值。 提示:使用numpy.array( )函数创建,通过列表生成数组对象。
import numpy as np
import random
list = []
sum = 0
for i in range(10):
n = int(random.random()*90 + 10)
list.append(n)
sum += n
arr1 = np.array(list)
print(arr1)
arr1.sort()
print(arr1[9],arr1[0],sum/10)
sum = 0
list2 = []
for i in range(5):
temp = []
for j in range(5):
n = int(random.random()*90 + 10)
sum += n
temp.append(n)
list2.append(temp)
arr2 = np.array(list2)
max,min= arr2[0][0],arr2[0][0]
for i in range(5):
for j in range(5):
if max < arr2[i][j] :
max = arr2[i][j]
if min > arr2[i][j] :
min = arr2[i][j]
print(arr2)
print(max,min,sum/25)
实验4.2:SciPy数据分析
题目描述:利用SciPy库完成2项编程任务。 (1)求解线性方程组。如图2-1所示。
(2)图像处理。预处理灰度图片效果如图2-2;平移处理未自动填充图片效果如图2-3;平移处理自动填充图片效果如图2-4;旋转处理图片效果如图2-5所示。 提示:使用scipy.mat( )和scipy.linalg.solve( )对线性方程求解; 使用scipy.ndimage和scipy.misc库对图像进行处理。使用pylab内部图库
import numpy as np
import scipy as sp
a = sp.mat('[5 2 3;2 3 -4;3 -4 -5]')
b = sp.mat('[6;7;8]')
solve = np.linalg.solve(a,b)
print(solve)
import pylab as pl
from scipy import misc
from scipy import ndimage
ascent = misc.ascent()
shifted_ascent = ndimage.shift(ascent,(50,50))
shifted_ascent2 = ndimage.shift(ascent,(50,50),mode = "nearest")
rotated_ascent = ndimage.rotate(ascent,30)
pl.imshow(ascent,cmap = pl.cm.gray)
pl.figure()
pl.imshow(shifted_ascent,cmap = pl.cm.gray)
pl.figure()
pl.imshow(shifted_ascent2,cmap = pl.cm.gray)
pl.figure()
pl.imshow(rotated_ascent,cmap = pl.cm.gray)
pl.figure()
实验4.3:Pandas数据分析
题目描述:利用Pandas库完成2项编程任务。 (1)利用列表、元组和字典分别创建3个一级索引的数据结构Series。实验效果如图3-1所示。 (2)利用字典和Series分别创建2个二级索引的数据结构DataFrame。实验效果如图3-2所示。 提示:使用pandas.Series( )和pandas.DataFrame( )分别创建一维Series和二维DataFrame数据结构;
from pandas import Series
from pandas import DataFrame
obj_list = [98,88,78,68]
obj_tuple = ('c++程序设计','Python程序设计','Java程序设计','物联网工程')
obj_dict = {'202101':['张三',18,'男','计科2002'],'202102':['李四',18,'男','计科2002'],'202103':['萌萌',18,'男','计科2002'],'202104':['王五',18,'女','计科2002']}
series_list = Series(obj_list,index=["No1","No2","No3","No4"])
series_tuple = Series(obj_tuple,index=["CId0001","CId0002","CId0003","CId0004"])
series_dict = Series(obj_dict)
print("(1) 通过list建立Series: ")
print(series_list)
print("(2) 通过tuple建立Series: ")
print(series_tuple)
print("(3) 通过dict建立Series: ")
print(series_dict)
obj1 = {
"学号":["202001","202002","202003","202004"],
"姓名":["张三","李四","萌萌","王五"],
"年龄":["18","18","18","18"],
"性别":["男","男","男","男"],
"班级":["计科2002","计科2002","计科2002","计科2002"]
}
series_dict1 = Series(["202002",'张三',18,'男','计科2002'],index=["学号","姓名","年龄","性别","班级"])
series_dict2 = Series(["202002",'张三',18,'男','计科2002'],index=["学号","姓名","年龄","性别","班级"])
series_dict3 = Series(["202002",'张三',18,'男','计科2002'],index=["学号","姓名","年龄","性别","班级"])
series_dict4 = Series(["202002",'张三',18,'男','计科2002'],index=["学号","姓名","年龄","性别","班级"])
df_obj1 = DataFrame(obj1)
df_obj2 = DataFrame([series_dict1,series_dict2,series_dict3,series_dict4])
print(df_obj1)
print("-----------")
print(df_obj2)
实验4.4:Matplotlib数据可视化 题目描述:利用CSV、Random、Datetime、Pandas和Matplotlib库完成5项编程任务。 (1)利用csv、random和datetime创建1个WPF商店2018年营业额模拟数据文件data.csv,此文件中包含两列数据(日期date、销量amount)。模拟数据随机生成共365条,数据日期date起于2018-01-01止于2018-12-31,数据销量amount的取值范围为[300,600]之间,如图4-1所示。 . . .
(2)利用pandas读取文件data.csv中数据,创建1个行列索引的数据结构DataFrame,并删除其中的所有缺失值。 (3)利用matplotlib生成折线图,按每天进行统计,显示商店每天的销量情况,并把图形保存为本地文件day_amount_plot.png。实验效果如图4-2所示。
(4)利用matplotlib生成柱状图,按月份进行统计,显示商店每月的销量情况,并把图形保存为本地文件month_amount_bar.png。实验效果如图4-3所示。同时,找出相邻两个月最大涨幅,并把涨幅最大的月份写入到文件maxMonth.txt中。
(5)利用matplotlib生成饼状图,按季度进行统计,显示商店4个季度的销量分布情况,并把图形保存为本地文件season_amount_pie.png。实验效果如图4-4所示。
提示:使用pandas.DataFrame( )创建二维DataFrame数据结构;使用matplotlib.pyplot库中的figure( )、plot( )、bar( )、pie( )、title( )、savefig( )和show( )等创建数据可视化图片,其功能分别设置图片大小、生成这线图、生成柱状图、生成饼状图、设置图片标题、保存图片和显示图片等。
import collections
import matplotlib.pyplot as plt
import numpy as np
import csv,random,datetime
with open(r"data.csv","w+",newline='') as csvfile:
wr = csv.writer(csvfile,dialect="excel")
wr.writerow(["data","amount"])
sd = datetime.date(2020,1,1)
for i in range(365):
amount = int(random.random()*301 + 300)
wr.writerow([sd,amount])
sd = sd + datetime.timedelta(days=1)
import pandas as pd
df = pd.read_csv("data.csv",encoding="cp936")
df.dropna()
plt.figure(figsize=(14,7))
plt.plot(df["data"],df["amount"],label = "day -> amount",color = "red",linewidth = 2)
plt.title("2020 Day Business Volume of MMMM Store")
plt.xlabel("day")
plt.ylabel("amont")
plt.xlim("2020-01-01","2020-12-31")
plt.legend()
plt.savefig("day_amount_plot.png")
plt.show()
df1 = df
df1["month"] = df1["data"].map(lambda x:x[:x.rindex('-')])
df1 = df1.groupby(by = "month",as_index=False).sum()
plt.figure(figsize=(14,7))
plt.bar(df1["month"],df1["amount"],label = "month -> amount ",color = "blue")
plt.title("2020 Month Business Volume of MMMM Store")
plt.xlabel("month")
plt.ylabel("amont")
plt.xlim("2020-01-01","2020-12-31")
plt.ylim(300,600)
plt.legend()
plt.savefig("month_amount_plot.png")
plt.show()
season1 = df1[:3]['amount'].sum()
season2 = df1[3:6]['amount'].sum()
season3 = df1[6:9]['amount'].sum()
season4 = df1[9:12]['amount'].sum()
plt.figure(figsize=(14,7))
plt.pie([season1,season2,season3,season4],labels = ["season1","season2","season3","season4"])
plt.title("2020 Season Business Volume of MMMM Store")
plt.savefig("Season_amount_plot.png")
plt.show()
实验4.5:简单GUI编程-学生成绩统计
题目描述:利用tkinter库完成2项GUI编程任务。 (1)利用tkinter库设计1个如图5-1所示的GUI图形界面。 (2)利用GUI面向对象编程方式实现学生四门课程的平均成绩计算功能。
提示:利用tkinter生成窗体、标签、文本框、命令按钮;利用grid实现窗体布局;利用GUI面向对象编程方式实现GUI编程封装。
import tkinter as t
from tkinter import Button, DoubleVar, Entry, IntVar, Label, Tk, messagebox
class ScoreCalculate:
def __init__(self):
win = Tk()
win.title("学生成绩统计")
lab_entNumber = Label(win,text = "C/C++程序设计:")
lab_entNumber.grid(row = 0,column = 0,padx = 5,pady = 5,sticky = "e")
self.VCpp = IntVar()
entNumber = Entry(win,width = 15,textvariable=self.VCpp)
entNumber.grid(row = 0,column = 1,padx = 5,pady = 5,sticky = "w")
Py = Label(win,text = "Python程序设计:")
Py.grid(row = 1,column = 0,padx = 5,pady = 5,sticky = "e")
self.VPy = IntVar()
ppy = Entry(win,width = 15,textvariable=self.VPy)
ppy.grid(row = 1,column = 1,padx = 5,pady = 5,sticky = "w")
Ja = Label(win,text = "Java程序设计:")
Ja.grid(row = 2,column = 0,padx = 5,pady = 5,sticky = "e")
self.VJa = IntVar()
Jja = Entry(win,width = 15,textvariable=self.VJa)
Jja.grid(row = 2,column = 1,padx = 5,pady = 5,sticky = "w")
WL = Label(win,text = "物联网工程:")
WL.grid(row = 3,column = 0,padx = 5,pady = 5,sticky = "e")
self.VIo = IntVar()
Wwl = Entry(win,width = 15,textvariable=self.VIo)
Wwl.grid(row = 3,column = 1,padx = 5,pady = 5,sticky = "w")
bt_Calculate = Button(win,text = "计算平均成绩:",command=self.Calculate)
bt_Calculate.grid(row = 4,column=0,columnspan=2,pady = 5)
AV = Label(win,text = "平均成绩:")
AV.grid(row = 5,column = 0,padx = 5,pady = 5,sticky = "e")
self.VAvg = DoubleVar()
Avv = Entry(win,width = 15,state="readonly",textvariable=self.VAvg)
Avv.grid(row = 5,column = 1,padx = 5,pady = 5,sticky = "w")
win.mainloop()
def Calculate(self):
try:
xC = float(self.VCpp.get())
xP = float(self.VPy.get())
xJ = float(self.VJa.get())
xIoT = float(self.VIo.get())
xAvg = (xC + xP + xJ + xIoT) / 4
self.VAvg.set(round(xAvg,1))
except :
messagebox.showerror(title="提示",message = "输入错误,请重新输入")
ScoreCalculate()
实验4.6:综合GUI编程-学生管理平台
题目描述:利用sqlites、tkinter、tkinter.messagebox和os库完成5项编程任务。 (1)使用SQLiteStudio.exe工具(工具来源参照第3次实验的SQLite3子实验)设计一个名为test.db数据库,库中创建两张数据表user(uid, upwd)和student(sid, sname, ssex, sage, sclass)。输入对应数据如图6-1和图6-2所示。
(2)设计一个用户登录类sLogin,布局如图6-3所示用户登录界面,实现“登录”和“退出”功能。
(3)设计一个主控管理类sMain,布局如图6-4所示主控管理界面,设计一级水平主菜单4项,包括“学生管理”、“”“课程管理”、“成绩管理”和“退出系统”。其中主菜单“成绩管理”可设计二级下拉菜单3项,包括“录入成绩”、“查询成绩”和“统计成绩”。(可以选做:下拉菜单“查询成绩”自行设计三级级联菜单2项,包括“理论成绩”和“实验成绩”。)实现菜单的功能设计与层次管理。
(4)设计一个学生管理类sManage,布局如图6-5所示学生管理界面,实现学生“录入”、“删除”、“修改”、“查询”、“查看”和关闭6个子功能。(以下给出单个“查询”和所有“查看”功能图示)
(5)通过菜单集成关联窗体。程序运行流程是:首先启动登录界面,查验数据库中用户名和密码有效后,然后才能进入主控管理界面,点击“学生管理”一级主菜单,可弹出显示学生管理界面,完成学生管理添、删、改、查基本功能。(另外选做:实现“课程管理”和“成绩管理”基本功能。) 提示: (1)数据表字段类型可全部设置为varchar类型,即字符串类型; (2)利用tkinter生成窗体、标签、文本框、命令按钮; (3)利用grid和place实现窗体布局和控件定位; (4)利用GUI面向对象编程方式实现GUI编程封装。 (5)利用SQL语句Insert、Delete、Update和Select实现添、删、改、查基本管理功能。
import tkinter as Tk
from tkinter import *
import tkinter.messagebox as messagebox
import sqlite3
import os
import tkinter as Tk
class sLogin:
"""登录界面"""
def __init__(self, login):
"""登录界面初始"""
self.frmLogin = login
self.frmLogin.geometry("320x200+380+200")
self.frmLogin.title("用户登录")
self.frame = Tk.Frame(self.frmLogin)
self.gridFrame()
def gridFrame(self):
"""登录界面布局"""
self.uid = StringVar()
self.uid.set("mzx")
self.upwd = StringVar()
self.upwd.set("123")
Label(self.frame).grid(row=0)
Label(self.frame, text="学生管理平台", fg="blue", font=(
"黑体", 20, "bold")).grid(row=1, columnspan=2)
Label(self.frame, text="用户名", width=5).grid(
row=2, column=0, padx=10, pady=10, sticky='e')
Entry(self.frame, textvariable=self.uid).grid(
row=2, column=1, pady=10, sticky='w')
Label(self.frame, text="密 码", width=5).grid(
row=3, column=0, padx=10, pady=5, sticky='e')
Entry(self.frame, textvariable=self.upwd,
show='*').grid(row=3, column=1, pady=5, sticky='w')
Button(self.frame, text="登录", width=13,
command=self.onLogin).grid(row=4, column=0, pady=10, sticky='w')
Button(self.frame, text="退出", width=13,
command=self.onExit).grid(row=4, column=1, pady=5, sticky='e')
self.frame.pack()
def onLogin(self):
"""登录进入"""
self.conn = sqlite3.connect("test.db")
cmd = self.conn.cursor()
sql = "select uid, upwd from user where uid='%s'" % self.uid.get()
cmd.execute(sql)
ds = cmd.fetchall()
if len(ds) == 0:
messagebox.showerror("登录失败", "账户不存在")
else:
xuid, xupwd = ds[0]
if xuid == self.uid.get() and xupwd == self.upwd.get():
self.hide()
root = Tk.Tk()
sMain(root)
root.mainloop()
else:
messagebox.showwarning("登录失败", "密码错误")
self.conn.close()
def hide(self):
"""隐藏窗体"""
self.frame.destroy()
self.frmLogin.withdraw()
def onExit(self):
"""退出登录"""
os._exit(0)
class sMain(object):
"""主控界面"""
def __init__(self, parent):
self.root = parent
self.root.geometry("1220x600+20+10")
self.root.title("学生管理平台v1.0")
self.frame = Tk.Frame(self.root)
self.menuFrame()
def menuFrame(self):
"""设计菜单"""
self.main = Tk.Menu(self.root)
self.subMenu3 = Menu(self.main)
self.subMenu3.add_command(label="录入成绩")
self.subMenu3.add_command(label="查询成绩")
self.subMenu3.add_command(label="统计成绩", command=self.onCalScore)
self.main.add_cascade(label="学生管理", command=self.onOpenStudent)
self.main.add_cascade(label="课程管理")
self.main.add_cascade(label="成绩管理", menu=self.subMenu3)
self.main.add_cascade(label="退出系统", command=self.onExit)
self.root["menu"] = self.main
self.frame.pack()
def onOpenStudent(self):
"""打开子窗体"""
sub = Tk.Toplevel()
sManage(sub)
def onCalScore(self):
"""统计成绩"""
pass
def onExit(self):
"""退出系统"""
os._exit(0)
class sManage():
"""学生管理"""
def __init__(self, child):
"""学生界面初始"""
self.frmStudent = child
self.frmStudent.geometry("600x400+40+70")
self.frmStudent.title("学生管理")
self.frame = Tk.Frame(self.frmStudent)
self.gridFrame()
def gridFrame(self):
"""学生界面布局"""
self.sid = StringVar()
self.sid.set('')
self.sname = StringVar()
self.sname.set('')
self.ssex = StringVar()
self.ssex.set('')
self.sage = StringVar()
self.sage.set('')
self.sclass = StringVar()
self.sclass.set('')
Label(self.frame).grid(row=0)
Label(self.frame, text="学生管理平台", fg="blue",
font=("黑体", 20, "bold")).grid(row=1, columnspan=4)
Label(self.frame, text="学 号", fg="red").grid(
row=2, column=0, pady=5, sticky='w')
Entry(self.frame, textvariable=self.sid).place(x=48, y=63)
Label(self.frame, text="姓 名").grid(
row=3, column=0, pady=5, sticky='w')
Entry(self.frame, textvariable=self.sname).place(
x=48, y=96)
Label(self.frame, text="性 别").place(x=231, y=96)
Entry(self.frame, textvariable=self.ssex).place(
x=281, y=96)
Label(self.frame, text="年 龄").grid(
row=4, column=0, pady=5, sticky='w')
Entry(self.frame, textvariable=self.sage).place(
x=48, y=129)
Label(self.frame, text="班 级").place(x=231, y=129)
Entry(self.frame, textvariable=self.sclass).place(
x=281, y=129)
Button(self.frame, text="录入", width=10,
command=self.onInsert).place(x=0, y=165)
Button(self.frame, text="删除", width=10,
command=self.onDelete).place(x=85, y=165)
Button(self.frame, text="修改", width=10,
command=self.onUpdate).place(x=170, y=165)
Button(self.frame, text="查询", width=10,
command=self.onSelect).place(x=255, y=165)
Button(self.frame, text="查看", width=10,
command=self.onLook).place(x=340, y=165)
Button(self.frame, text="关闭", width=10,
command=self.onHide).place(x=425, y=165)
self.vShow = StringVar()
self.vShow.set('')
Listbox(self.frame, listvariable=self.vShow,
width=72, height=9).grid(row=5, columnspan=4, pady=50, sticky='e')
self.frame.pack()
def onInsert(self):
"""录入学生"""
self.conn = sqlite3.connect("test.db")
self.cmd = self.conn.cursor()
sql = "select sid, sname, ssex, sage, sclass from student where sid='%s'" % self.sid.get()
self.cmd.execute(sql)
ds = self.cmd.fetchall()
if len(ds) == 1:
messagebox.showerror(
"录入失败", "学生" + self.sid.get() + "存在,不允许重复录入...")
else:
sql = "insert into student(sid,sname,ssex,sage,sclass) values('%s','%s','%s','%s','%s')" \
% (self.sid.get(), self.sname.get(), self.ssex.get(), self.sage.get(), self.sclass.get())
self.cmd.execute(sql)
self.conn.commit()
messagebox.showinfo("录入成功", "录入学生" + self.sid.get() + "成功...")
self.cmd.close()
self.conn.close()
def onDelete(self):
"""删除学生"""
self.conn = sqlite3.connect("test.db")
self.cmd = self.conn.cursor()
sql = "select sid, sname, ssex, sage, sclass from student where sid='%s'" % self.sid.get()
self.cmd.execute(sql)
ds = self.cmd.fetchall()
if len(ds) == 0:
messagebox.showerror("删除失败", "学生" + self.sid.get() + "不存在,删除失败...")
else:
sql = "delete from student where sid='%s'" % self.sid.get()
self.cmd.execute(sql)
self.conn.commit()
messagebox.showinfo("删除成功", "删除学生" + self.sid.get() + "成功...")
self.cmd.close()
self.conn.close()
def onUpdate(self):
"""修改学生"""
self.conn = sqlite3.connect("test.db")
self.cmd = self.conn.cursor()
sql = "select sid, sname, ssex, sage, sclass from student where sid='%s'" % self.sid.get()
self.cmd.execute(sql)
ds = self.cmd.fetchall()
if len(ds) == 0:
messagebox.showerror("修改失败", "学生" + self.sid.get() + "不存在,修改失败...")
else:
sql = "update student set sname='%s', ssex='%s', sage='%s', sclass='%s' where sid='%s'" \
% (self.sname.get(), self.ssex.get(), self.sage.get(), self.sclass.get(), self.sid.get())
self.cmd.execute(sql)
self.conn.commit()
messagebox.showinfo("修改成功", "修改学生" + self.sid.get() + "成功...")
self.cmd.close()
self.conn.close()
def onSelect(self):
"""查询学生"""
self.conn = sqlite3.connect("test.db")
self.cmd = self.conn.cursor()
sql = "select sid, sname, ssex, sage, sclass from student where sid='%s'" % self.sid.get()
self.cmd.execute(sql)
ds = self.cmd.fetchall()
if len(ds) == 0:
messagebox.showerror("查询失败", "查询学生" + self.sid.get() + "不存在...")
else:
xsid, xsname, xssex, xsage, xsclass = ds[0]
self.sid.set(xsid)
self.sname.set(xsname)
self.ssex.set(xssex)
self.sage.set(xsage)
self.sclass.set(xsclass)
strResult = xsid+','+xsname+','+xssex+','+xsage+','+xsclass
self.vShow.set(strResult)
self.cmd.close()
self.conn.close()
def onLook(self):
"""查看学生"""
self.conn = sqlite3.connect("test.db")
self.cmd = self.conn.cursor()
sql = "select sid, sname, ssex, sage, sclass from student"
self.cmd.execute(sql)
ds = self.cmd.fetchall()
if len(ds) == 0:
messagebox.showerror("查看失败", "查询学生" + self.sid.get() + "不存在...")
else:
strResult = ''
for i in range(len(ds)):
xsid, xsname, xssex, xsage, xsclass = ds[i]
strResult += xsid+','+xsname+','+xssex+',' + \
xsage+','+xsclass+' '
self.vShow.set(strResult)
self.cmd.close()
self.conn.close()
def onHide(self):
"""隐藏窗体"""
self.frame.destroy()
self.frmStudent.withdraw()
if __name__ == "__main__":
"""主程序启动入口"""
login = Tk.Tk()
sLogin(login)
login.mainloop()
|