这题目内容太多了,折腾半天,可能有些理解不一定正确,仅供参考
#1、读取文件team.xlsx数据,其中'name':名字, 'team':所属团队, '1':语文分数, '2':数学分数, '3':英语分数, '4':政治分数,完成以下任务:
import pandas as pd
df = pd.read_excel('team.xlsx')
#(1)查询该数据的索引、所有值、列名、数据类型、元素个数、维度以及形状。
print(f'索引:{df.index}')
print(f'所有值:{df[::]}')
print(f'列名:{",".join([c for c in df.columns])}')
print(f'数据类型:{[type(x) for x in df[0:]]}')
print(f'元素个数:{len(df.index)}')
print(f'维度:{[c for c in df.columns][1:]}')
print(f'形状:{df[::].shape}')
#(2)访问该数据中’name’、’team’中的前5行数据。
top5 = df[['name','team']][:5]
print(top5)
# (3)访问该数据所属团队为B组中的成员名字,并筛选出B组中'1'大于60分的同学。
# B组成员
b_lst = df[df['team']=='B'].loc[:,'name']
print(b_lst.to_list())
#B组中'1'大于60分的同学
df = df[df['team']=='B']
b_lst1 = df[df['Q1']>60].loc[:,'name']
print(b_lst1.to_list())
# (4)在文件最后添加一列’tol’,意为该成员的四门课的分数总和。
data = df[['Q1','Q2','Q3','Q4']]
tol = [data.loc[i].sum() for i in data.index]
df['tol'] = tol
print(df)
# (5)对数值型和’team’列数据分别进行描述性统计。
print(f'A组成员占总人数{len(df[df["team"]=="A"].index)/len(df.index)*100}%')
print(f'B组成员占总人数{len(df[df["team"]=="B"].index)/len(df.index)*100}%')
print(f'C组成员占总人数{len(df[df["team"]=="C"].index)/len(df.index)*100}%')
print(f'D组成员占总人数{len(df[df["team"]=="D"].index)/len(df.index)*100}%')
print(f'E组成员占总人数{len(df[df["team"]=="E"].index)/len(df.index)*100}%')
print(f'语文成绩及格率{len(df[df["Q1"]>=60].index)/len(df.index)*100}%')
print(f'数学成绩及格率{len(df[df["Q2"]>=60].index)/len(df.index)*100}%')
print(f'英语成绩及格率{len(df[df["Q3"]>=60].index)/len(df.index)*100}%')
print(f'政治成绩及格率{len(df[df["Q4"]>=60].index)/len(df.index)*100}%')
# (6)对该数据按所属团队进行分类,查看每个团队的大小,并计算每个团队的1', '2', '3', '4'四门课的总分和平均分。
a = df[df["team"]=="A"]
b = df[df["team"]=="B"]
c = df[df["team"]=="C"]
d = df[df["team"]=="D"]
e = df[df["team"]=="E"]
for i,t in zip([a,b,c,d,e],['A','B','C','D','E']):
num = len(i.index)
sum_1 = i["Q1"].sum()
avg_1 = round(sum_1/num,2)
sum_2 = i["Q2"].sum()
avg_2 = round(sum_2/num,2)
sum_3 = i["Q3"].sum()
avg_3 = round(sum_3/num,2)
sum_4 = i["Q4"].sum()
avg_4 = round(sum_4/num,2)
print(f'团队{t}有{num}人,语文总分/平均分:{sum_1}/{avg_1},数学总分/平均分:{sum_2}/{avg_2},英语总分/平均分:{sum_3}/{avg_3},政治总分/平均分:{sum_4}/{avg_4}')
# 2、读取文件team.xlsx数据,其中'name':名字, 'team':所属团队, '1':语文分数, '2':数学分数, '3':英语分数, '4':政治分数,完成以下任务:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('team.xlsx')
# (1)画出'1'、 '2'、'3'、 '4'四门课分数的散点图和折线图。
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['font.sans-serif']=['SimHei']
#散点图
ax1 = df.plot.scatter(x='name', y='Q1', color='r', label='Q1')
df.plot.scatter(x='name', y='Q2', color='b', label='Q2', ax=ax1)
df.plot.scatter(x='name', y='Q3', color='y', label='Q3', ax=ax1)
df.plot.scatter(x='name', y='Q4', color='g', label='Q3', ax=ax1)
plt.xticks('')
#折线图
df.plot(kind='line',x='name', y=['Q1', 'Q2', 'Q3', 'Q4'],subplots=True,layout=(2, 2),figsize=(10, 5))
plt.show()
# (2)按所属团队进行分类,画出每个团队四门课平均分的直方图、饼图和箱线图。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('team.xlsx')
a = df[df["team"]=="A"]
b = df[df["team"]=="B"]
c = df[df["team"]=="C"]
d = df[df["team"]=="D"]
e = df[df["team"]=="E"]
a_avg = [round(a[q].sum()/len(a.index),2) for q in ['Q1','Q2','Q3','Q4']]
b_avg = [round(b[q].sum()/len(b.index),2) for q in ['Q1','Q2','Q3','Q4']]
c_avg = [round(c[q].sum()/len(c.index),2) for q in ['Q1','Q2','Q3','Q4']]
d_avg = [round(d[q].sum()/len(d.index),2) for q in ['Q1','Q2','Q3','Q4']]
e_avg = [round(e[q].sum()/len(e.index),2) for q in ['Q1','Q2','Q3','Q4']]
df_hist = pd.DataFrame({'A':a_avg, 'B':b_avg, 'C':c_avg, 'D':d_avg, 'E':e_avg}, columns=['A','B','C','D','E'],index=['Q1','Q2','Q3','Q4'])
#直方图
df_hist.hist(color='r', alpha=0.5, bins=20)
#饼图
df_hist.plot.pie(subplots=True, figsize=(10, 5))
#箱线图
df_hist.plot.box(figsize=(10, 5))
plt.show()
# 3、读取文件countries-aggregated.csv数据,其中'Date':日期, 'Country':国家, 'Confirmed'、 'Recovered'、 'Deaths':当日累计确诊、康复、死亡人数,完成以下任务:
# (1)查询中国、美国的累计确诊人数,并画出折线图。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('countries-aggregated.csv')
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['font.sans-serif']=['SimHei']
cn = df[df['Country']=='China']
us = df[df['Country']=='US']
plt.figure(figsize=(9,6))
plt.title('中国、美国的累计确诊人数')
plt.plot(cn.loc[:,'Date'], cn.loc[:,'Confirmed'], color='green', label='China')
plt.plot(cn.loc[:,'Date'], us.loc[:,'Confirmed'], color='red', label='US')
plt.ylabel('确诊人数(百万)')
plt.xlabel('日期')
plt.yticks(range(0,1500000,100000))
plt.xticks(cn.loc[:,'Date'][::10],)
plt.show()
# (2)查询2020/5/4日确诊病例在1万以上的国家中死亡率(死亡人数/确诊人数)排名前十的国家,并画出直方图。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('countries-aggregated.csv')
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['font.sans-serif']=['SimHei']
data = df[df['Date']=='2020/5/4'][df['Confirmed']>10000]
data['newc'] = pd.DataFrame(df['Deaths']/df['Confirmed'])
data.sort_values(by="newc" , inplace=True, ascending=False)
top10 = data.head(10)['newc']
top10.hist(color='r', alpha=0.5, bins=25)
plt.show()
# 4、import pandas as pd
# pd.Series(pd.date_range('1920','2021'))
# 使用以上语句生成100年的时间序列,完成以下操作:
# (1)找出100年中的劳动节
import pandas as pd
import time
import matplotlib.pyplot as plt
dates = pd.Series(pd.date_range('1920','2021'))
lst = [str(d).split(' ')[0] for d in list(dates) if '-05-01' in str(d)]
print(lst)
# (2)计算出劳动节分别为星期一到星期日的天数。
lst = [time.strptime(str(d), "%Y-%m-%d %X").tm_wday for d in list(dates) if '-05-01' in str(d)]
weeks = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
weekinfo = {weeks[i]:lst.count(i) for i in range(7)}
print(weekinfo)
# (3)绘制劳动节分别为星期一到星期日的天数数量的直方图。
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['font.sans-serif']=['SimHei']
plt.hist(weekinfo.values())
plt.show()