代码如下:
import numpy as np
import pandas as pd
#
# 构造学生成绩
# 模拟50个学生的语文(chinese),数学(math),英语(english)三科成绩,存储在DataFrame中,
# 使用学生编号["01", "02", ..., "50"]作为index
def createGrades(N):
index = []
for i in range(1, N + 1):
index.append(str(i) if i > 9 else "0" + str(i))
G = pd.DataFrame(np.zeros((N, 4)),
columns=["chinese", "math", "english", "total"],
index=index)
G.chinese = np.floor(np.random.normal(70, 10, N))
G.math = np.floor(np.floor(np.random.normal(80, 10, N)))
G.english = np.floor(np.random.normal(75, 10, N))
G.chinese[G.chinese > 100] = 100
G.chinese[G.chinese < 0] = 0
G.math[G.math > 100] = 100
G.math[G.math < 0] = 0
G.english[G.english > 100] = 100
G.english[G.english < 0] = 0
G.total = G.math + G.chinese + G.english
return G
def maxminGrade(G):
print("语文最高分学生:")
print(G.query("chinese == chinese.max()"))
print("语文最低分学生:")
print(G.query("chinese == chinese.min()"))
print("数学最高分学生:")
print(G.query("math == math.max()"))
print("数学最低分学生:")
print(G.query("math == math.min()"))
print("英语最高分学生:")
print(G.query("english == english.max()"))
print("英语最低分学生:")
print(G.query("english == english.min()"))
print("总分最高分学生:")
print(G.query("total == total.max()"))
print("总分最低分学生:")
print(G.query("total == total.min()"))
def sortGrade(G):
print("按照语文成绩进行排序:")
# ascending=False从高到低排序
# ascending=True从低到高排序
print(G.sort_values(by="chinese", ascending=False))
print("按照数学成绩进行排序:")
print(G.sort_values(by="math", ascending=False))
print("按照英语成绩进行排序:")
print(G.sort_values(by="english", ascending=False))
print("按照总分成绩进行排序:")
print(G.sort_values(by="total", ascending=False))
def rangeGrade(G):# 统计0-60、60-80、80-100各个分数段总共有多少
index = ["[0, 60)", "[60, 80)", "[80, 100]"]
R = pd.DataFrame(np.zeros((len(index), 3)),
columns=["chinese", "math", "english"],
index=index)
R.loc["[0, 60)", "chinese"] = (G.chinese < 60).sum()
R.loc["[60, 80)", "chinese"] = ((G.chinese >= 60) & (G.chinese < 80)).sum()
R.loc["[80, 100]", "chinese"] = ((G.chinese >= 80) & (G.chinese <= 100)).sum()
R.loc["[0, 60)", "math"] = (G.math < 60).sum()
R.loc["[60, 80)", "math"] = ((G.math >= 60) & (G.math < 80)).sum()
R.loc["[80, 100]", "math"] = ((G.math >= 80) & (G.math <= 100)).sum()
R.loc["[0, 60)", "english"] = (G.english < 60).sum()
R.loc["[60, 80)", "english"] = ((G.english >= 60) & (G.english < 80)).sum()
R.loc["[80, 100]", "english"] = ((G.english >= 80) & (G.english <= 100)).sum()
return R
if __name__ == "__main__":
N = 50
G = createGrades(N)
print(G)
maxminGrade(G)
sortGrade(G)
print(rangeGrade(G))