您的位置:首页 > 其它

如何读取CSV文件,格式化数据,统计生日出现的次数

2017-10-04 13:16 323 查看

如何读取CSV文件, 并对生日出现的次数

本文将使用python语言,导入一个CSV文件,对文件数据进行处理,然后统计其中各个时间的生日出现的次数

读取CSV文件

列表的操作

字符串的不可变性

函数的定义和调用

如何同时列表中元素的个数

数据格式

afed
yearmonthdate_of_monthday_of_weekbirths
19941168096
19941277772
199413110142
199414211248
199415311053
199416411406
199417511251
19941868653
19941977910

读取文件代码

def read_csv(filename):
string_data = open(filename).read()
string_list = string_data.split("\n")[1:]
final_list = []

for row in string_list:
string_fields = row.split(",")
int_fields = []
for value in string_fields:
int_fields.append(int(value))
final_list.append(int_fields)
return final_list

cdc_list = read_csv("US_births_1994-2003_CDC_NCHS.csv")


统计生日出现的次数

def month_births(list_1):
births_per_month = {}
for item in list_1:
if item[1] in births_per_month:
births_per_month[item[1]] += item[-1]
else:
births_per_month[item[1]] = item[-1]
return births_per_month
cdc_month_births = month_births(cdc_list)

print(cdc_month_births)

result:
{1: 3232517, 2: 3018140, 3: 3322069, 4: 3185314, 5: 3350907, 6: 3296530, 7: 3498783, 8: 3525858, 9: 3439698, 10: 3378814, 11: 3171647, 12: 3301860}


Lynda.com是个非常不错的学习网站, 里面有很多高端的python学习课程,本人高性价比的新用户代注册和老用户激活续期服务,具体可查看:

Lynda.com会员Lynda账号Premium私人定制观看所有课程练习文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐