实现功能:
从入院时间这一列(格式:2008-04-21)提取年份(例如2008),随后按照年份统计记录数。
输入:excel文件,含有2231条记录,含有入院时间这一列;
输出:统计出每个年份各有多少条记录数。
实现代码:
1 | import seaborn as sns |
2 | import numpy as np |
3 | from xlrd import xldate_as_datetime |
4 | import xlrd |
5 | import matplotlib.pyplot as plt |
6 | |
7 | |
8 | def Statistics_by_time(file): |
9 | workbook = xlrd.open_workbook("F:\数据杂坛\data\患者按地区研究信息_2231 .xls") # 文件路径 |
10 | worksheet=workbook.sheet_by_index(0) |
11 | |
12 | nrow=worksheet.nrows |
13 | print(nrow) |
14 | |
15 | down1999=e1999=e2000=e2001=e2002=e2003=e2004=e2005=e2006=e2007=e2008=e2009=up2009=0 |
16 | |
17 | for i in range(1,nrow): |
18 | row= worksheet.row_values(i) |
19 | if row[13]!='': |
20 | d1=xldate_as_datetime(row[13],0).strftime('%Y') |
21 | print(d1,type(d1)) |
22 | if int(d1)<1999: |
23 | down1999=down1999+1 |
24 | elif d1=="1999": |
25 | e1999=e1999+1 |
26 | elif d1=="2000": |
27 | e2000=e2000+1 |
28 | elif d1=="2001": |
29 | e2001=e2001+1 |
30 | elif d1=="2002": |
31 | e2002=e2002+1 |
32 | elif d1=="2003": |
33 | e2003=e2003+1 |
34 | elif d1=="2004": |
35 | e2004=e2004+1 |
36 | elif d1=="2005": |
37 | e2005=e2005+1 |
38 | elif d1=="2006": |
39 | e2006=e2006+1 |
40 | elif d1=="2007": |
41 | e2007=e2007+1 |
42 | elif d1=="2008": |
43 | e2008=e2008+1 |
44 | elif d1=="2009": |
45 | e2009=e2009+1 |
46 | elif int(d1)>2009: |
47 | up2009=up2009+1 |
48 | |
49 | print(down1999,e1999,e2000,e2001,e2002,e2003,e2004,e2005,e2006,e2007,e2008,e2009,up2009) |
50 | print(np.mean([down1999,e1999,e2000,e2001,e2002,e2003,e2004,e2005,e2006,e2007,e2008,e2009,up2009])) |
51 | |
52 | font = {'family': 'Times New Roman', |
53 | 'size': 16, |
54 | } |
55 | sns.set(font_scale=1.2) |
56 | plt.rc('font',family='Times New Roman') |
57 | |
58 | X = ['~1999', '1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009'] |
59 | Y = [down1999,e1999,e2000,e2001,e2002,e2003,e2004,e2005,e2006,e2007,e2008,e2009] |
60 | Z=[down1999,e1999,e2000,e2001,e2002,e2003,e2004,e2005,e2006,e2007,e2008,e2009]/np.sum(Y) |
61 | |
62 | fig = plt.figure(figsize=(9,6)) |
63 | plt.bar(X, Y, 0.4, color="b") |
64 | plt.plot(X, Y, 0.4, color="g") |
65 | plt.xlabel("Year of admission of h-SLE patient(year)", fontsize=14) |
66 | plt.ylabel("Number of h-SLE patients(cases)", fontsize=14) |
67 | plt.title("Analysis of the year of admission of h-SLE patient", fontsize=14) |
68 | |
69 | for a, b in zip(X, Z): # 柱子上的数字显示 |
70 | plt.text(a, b, '%.2f%%' % (b*100), ha='center', va='top', fontsize=12) |
71 | for a,b in zip(X,Y): #柱子下的数字显示 |
72 | plt.text(a,b,'%d'%b,ha='center',va='bottom',fontsize=12) |
73 | |
74 | plt.show() |
75 | |
76 | if __name__=='__main__': |
77 | Statistics_by_time("F:\数据杂坛\data\患者按地区研究信息_2231 .xls") |
实现效果:
统计出的各个年份的记录数:
绘制的柱状图:
喜欢记得点赞,收藏,转发,加关注(V订阅号:数据杂坛),将持续更新!
声明:我要去上班所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,版权归原作者不再依然所有,原文出处。若您的权利被侵害,请联系删除。
本文标题:(python获取当前时间日期)(python 日期格式转换)
本文链接:https://www.51qsb.cn/article/m86k8.html