網站首頁 編程語言 正文
1 數據概覽
學生課程成績:studentID、name、english、chinese、math,存在一定缺失值
2 任務定義
基于學生課程成績文件,使用pandas和sqlite3將學生信息輸入SQLite數據庫,請在完成對應數據庫操作后分析學生課程成績信息,計算各科目平均分并給出總分排名。
3 實現步驟
3.1 利用pandas讀取學生信息
import pandas as pd
import sqlite3
# 利用pandas讀取數據
student_df=pd.read_csv("./Dataset/student_grades.csv",encoding='utf-8-sig')
3.2 利用sqlite3創建數據庫和學生表
# 創建學生成績數據庫
conn=sqlite3.connect("./Database/Student_grade.db")
## 創建游標
cursor=conn.cursor()
## 創建成績表
try:
# 判斷表是否存在, 存在則先刪除
dropif_sql='Drop TABLE IF EXISTS student_grades;'
create_sql='''
CREATE TABLE student_grades
(
studentID varchar(64),
studentName varchar(64),
scoreEnglish float(64),
scoreChinese float(64),
scoreMath float(64)
)
'''
cursor.execute(dropif_sql)
cursor.execute(create_sql)
except:
print("Create table failed!")
3.3 利用sqlite3將學生信息存入數據庫
# 將學生信息存入數據庫
for i in range(student_df.shape[0]):
print(student_df.loc[i,:].to_list())
# 插入語句
insert_sql='''
INSERT INTO student_grades(studentID, studentName, scoreEnglish, scoreChinese, scoreMath)
Values('%s','%s','%f','%f','%f')'''%(
str(student_df.loc[i,'StudentID']),
str(student_df.loc[i,'name']),
student_df.loc[i,'english'],
student_df.loc[i,'chinese'],
student_df.loc[i,'math'],
)
# 執行語句
cursor.execute(insert_sql)
# 事物提交
conn.commit()
3.4 將李四數學成績70錄入SQLite數據庫
# 錄入李四的數學成績
grade_LiSi=70
# 更新語句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10002'.format(grade_LiSi)
# 執行語句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查詢錄入李四成績后的信息
select_sql='SELECT * FROM student_grades;'
# 執行語句
results=cursor.execute(select_sql)
# 遍歷輸出
for info in results.fetchall():
print(info)
3.5 將數據庫中的王五數學成績改為85
# 更新王五的數學成績
grade_WangWu=85
# 更新語句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10003'.format(grade_WangWu)
# 執行語句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查詢王五的成績
select_sql='SELECT * FROM student_grades WHERE studentID=10003;'
# 執行語句
results=cursor.execute(select_sql)
# 遍歷輸出
for info in results.fetchall():
print(info)
3.5 計算學生的各科平均分,并給出總分排名
# 查詢數據
select_sql='SELECT * FROM student_grades;'
# 執行語句
results=cursor.execute(select_sql)
# 計算各科平均分以及總分排名
english_lst=[]
chinese_lst=[]
math_lst=[]
total_dct={}
for info in results.fetchall():
english_lst.append(info[2])
chinese_lst.append(info[3])
math_lst.append(info[4])
total_dct[info[1]]=sum(info[2:])
# 計算平均分的函數
def average_score(lst):
return round(sum(lst)/len(lst),2)
# 輸出結果
print("英語平均分為:", average_score(english_lst))
print("語文平均分為:", average_score(chinese_lst))
print("數學平均分為:", average_score(math_lst))
print("總成績排名為:", sorted(total_dct.items(), key=lambda x:x[1], reverse=True))
4 小小的總結
在Python中使用sqlite3:
連接數據庫:conn=sqlite3.connect(filename),如果數據庫不存在,會自動創建再連接。創建游標:cursor=conn.cursor(),SQL的游標是一種臨時的數據庫對象,即可以用來
存放在數據庫表中的數據行副本,也可以指向存儲在數據庫中的數據行的指針。游標提供了在逐行的基礎上操作表中數據的方法。
運用sqlite3運行SQL語句的框架:
① 定義sql語句,存儲到字符串sql中
② 使用游標提交執行語句:cursor.execute(sql)
③ 使用連接提交事務:conn.commit()
原文鏈接:https://blog.csdn.net/fangyibo24/article/details/123476900
相關推薦
- 2023-03-23 python跳出雙層循環的方法_python
- 2022-01-30 tortoiseGit推送每次需要輸入密碼,解決方案
- 2022-06-25 iOS實現文件下載功能_IOS
- 2022-08-03 python中的三種注釋方法_python
- 2023-04-08 react中實現拖拽排序react-dnd功能_React
- 2022-10-21 Golang驗證器之validator是使用詳解_Golang
- 2023-02-28 ts之 命名空間 namespace、三斜線指令、聲明文件(declare 聲明ts的變量函數第三方
- 2022-05-27 android實現簡單拼圖游戲_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支