运行

使用环境

python 2.7(运行过程中缺少包自行安装)

jupyter 1.0.0 安装使用

运行代码

##cd进.ipynb 所在目录

cd python

## 开启 jupyter

jupyter notebook

捕获.PNG

点击对应文件(注意要先把数据集下载到对应目录)

然后点击运行,等待一段时间就会出现结果。结果如下图。

捕获.PNG

捕获.PNG等等......

源码分析

源数据数据格式

捕获.PNG

源数据就是id与分年份与性别的统计数据(一份有大洲数据)。

代码分析

2.1 us_baby_names

## 读取csv数据到data中

data = pd.read_csv('./dataset/NationalNames.csv')

##展示data数据头部5条信息

data.head()

## 查看数据详情

data.info()

# 将“姓名”和其数量进行统计,并放入“字典”变量中

names_dict = dict()

# 由于数据量多,耗时较长

for index, row in data.iterrows():

# 按行遍历数据 如果没有该名字,则新建字典index否则加一

if row['Name'] not in names_dict:

names_dict[row['Name']] = row['Count']

else:

names_dict[row['Name']] += row['Count']

# 使用Counter计数器的most_common函数进行统计。

# 返回最常用的元素及其计数的列表

top_10 = Counter(names_dict).most_common(10)

print '全美流行的婴儿名字top10:'

for pair in top_10:

print '姓名:%s -> 数量:%i' %(pair[0], pair[1])

def average_length_data_transform():

"""

统计每年男性、女性姓名的平均长度

"""

# 按行遍历数据

years = []

# 女性姓名

female_average_length = []

female_average_name_length = dict()

# 男性姓名

male_average_length = []

male_average_name_length = dict()

for index, row in data.iterrows():

# 按行遍历数据集

if row['Gender'] == 'F':

# 女性

# 获取当前年份

curr_year = row['Year']

# 当前记录姓名长度

curr_name_length = len(row['Name'])

if curr_year not in female_average_name_length:

# 如果当前年份不在“字典”中,放入字典中

# 比如: 1880年第一条女性记录:1 Mary 1880 F 7065,将做如下处理

# {1880: [4, 1]}

female_average_name_length[curr_year] = [curr_name_length, 1]

else:

# 比如: 1880年第二条女性记录: 2 Anna 1880 F 2604,将做如下处理

# {1880: [4+4, 1+1]} -> {1880: [8, 2]}

female_average_name_length[curr_year][0] += curr_name_length

female_average_name_length[curr_year][1] += 1

else:

# 男性

# 处理过程同上

curr_year = row['Year']

curr_name_length = len(row['Name'])

if curr_year not in male_average_name_length:

male_average_name_length[curr_year] = [curr_name_length, 1]

else:

male_average_name_length[curr_year][0] += curr_name_length

male_average_name_length[curr_year][1] += 1

# 遍历处理后的字典

# 女性

for key, value in female_average_name_length.items():

years.append(key)

female_average_length.append(float(value[0]) / value[1])

# 男性

for key, value in male_average_name_length.items():

years.append(key)

male_average_length.append(float(value[0]) / value[1])

return (female_average_length, female_average_name_length, male_average_length, male_average_name_length)

# years = [1880, 1881, ..., 2014]

years = range(1880, 2015)

# 使用matplotlib进行数据可视化

f, ax = plt.subplots(figsize=(10, 6))

# 设置x轴数值范围

ax.set_xlim([1880, 2014])

# years为x轴,average_length为y轴

# 女性曲线为红色,男性为蓝色

plt.plot(years, female_average_length, label='Average length of female names', color='r')

plt.plot(years, male_average_length, label='Average length of male names', color='b')

# 设置x,y轴标签

ax.set_ylabel('Length of name')

ax.set_xlabel('Year')

# 设置图像名称

ax.set_title('Average length of names')

# 设置图例

legend = plt.legend(loc='best', frameon=True, borderpad=1, borderaxespad=1)

捕获.PNG

唯一姓名分析

top_in_each_year = dict()

years = range(1880, 2015)

for each_year in years:

#获取每一年的数据(为啥这样用???)

each_year_data = data[data['Year'] == each_year]

top_in_each_year[each_year] = dict()

#获取每一年的某一姓名的数量

for index, row in each_year_data.iterrows():

# 为什么不是+=(可能数据是不重复的??)

top_in_each_year[each_year][row['Name']] = row['Count']

all_sum = []

top_25_sum = []

#按照年份遍历数组

for year, names_in_year in top_in_each_year.items():

#将当前年份总人数添加到all_sum中

all_sum.append(sum(Counter(names_in_year).values()))

top_25 = Counter(names_in_year).most_common(25)

sum_temp = 0

for pair in top_25:

sum_temp += pair[1]

# 将当前出现最频繁的25个名字总数相加和加入到列表

top_25_sum.append(sum_temp)

#可视化

......

image.png

2.2 tv_inspired_baby_names

def plotname(name, gender):

"""

对姓名及性别进行可视化

"""

# 找到符合条件的数据

data_named = data[(data.Name==name) & (data.Gender==gender)]

plt.figure(figsize=(10,6))

# 对数据的年份,数量进行可视化

plt.plot(data_named.Year,data_named.Count,'g-')

plt.title('%s name variation over time'%name)

plt.ylabel('counts')

plt.xticks(data_named.Year,rotation='vertical')

# 设置x轴数值范围

plt.xlim([1985,2015])

plt.show()

MMP 简书又挂了,图片上传不了...

总结

这份代码其实就是python以及可视化,数据处理等包的简单使用,感觉并没有很大的难度,主要是环境搭建和一些数据处理函数的使用。