如何读取CSV文件, 并对生日出现的次数
本文将使用python语言,导入一个CSV文件,对文件数据进行处理,然后统计其中各个时间的生日出现的次数
- 读取CSV文件
- 列表的操作
- 字符串的不可变性
- 函数的定义和调用
- 如何同时列表中元素的个数
数据格式
year | month | date_of_month | day_of_week | births |
---|---|---|---|---|
1994 | 1 | 1 | 6 | 8096 |
1994 | 1 | 2 | 7 | 7772 |
1994 | 1 | 3 | 1 | 10142 |
1994 | 1 | 4 | 2 | 11248 |
1994 | 1 | 5 | 3 | 11053 |
1994 | 1 | 6 | 4 | 11406 |
1994 | 1 | 7 | 5 | 11251 |
1994 | 1 | 8 | 6 | 8653 |
1994 | 1 | 9 | 7 | 7910 |
读取文件代码
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私人定制观看所有课程练习文件