import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
path = 'C:\\Users\\peach\\Desktop\\python_code\\names'
os.chdir(path)
# 修改读取文件的路径
years = range(1880,2018)
pieces = []
columns = ['name','sex','births']
for year in years:
path = 'yob%d.txt' % year
frame = pd.read_csv(path,names=columns)
frame['year'] = year
pieces.append(frame)
# 批量读取文件
names = pd.concat(pieces,ignore_index=True)
# 将所有的内容放进一个dataframe
total_births = names.pivot_table('births',index='year',columns='sex',aggfunc='sum')
# 按性别和年份划分的出生总数
total_births.plot(title='Total births by sex and year')
def add_prop(group):
group['prop']=group.births/group.births.sum()
return group
# 创建一个添加prop列,以计算每个名字按照年份、性别的占比
names = names.groupby(['year','sex']).apply(add_prop)
names.groupby(['year','sex']).prop.sum()
# 验证所有组的prop列总计为1
def get_top1000(group):
return group.sort_values(by='births',ascending=False)[:1000]
# 创建一个筛选出生数前1000名
grouped = names.groupby(['year','sex'])
top1000 = grouped.apply(get_top1000)
top1000.reset_index(inplace=True,drop=True)
boys = top1000[top1000.sex=='M']
girls = top1000[top1000.sex=='F']
# 将top1000里的男孩和女孩分开
top1000.query('year==2017 & sex=="M"')
# 查找2017年出生的top1000的男孩名
total_births = top1000.pivot_table('births',index='year',columns='name',aggfunc=sum)
subset =total_births[['John','Jacky','Joe','Joey']]
subset.plot(subplots=True,figsize=(12,10),grid=False,title='Number of births per year')
table = top1000.pivot_table('prop',index='year',columns='sex',aggfunc=sum)
figsize = (12,4)
table.plot(title='Sum of top1000.prop by year and sex',yticks=np.linspace(0,1.2,13),)
# 查看top1000的名字覆盖的范围
df = boys[boys.year==2017]
# 筛选2017年的top1000男孩名
prop_cumsum = df.sort_values(by='prop',ascending=False).prop.cumsum()
# 按照 prop列求累计总和
prop_cumsum.values.searchsorted(0.5)
# 查找累积和为0.5的位置
def get_quantile_count(group,q=0.5):
group = group.sort_values(by='prop',ascending=False)
return group.prop.cumsum().values.searchsorted(q)+1
diversity =top1000.groupby(['year','sex']).apply(get_quantile_count)
# 按年份、性别求取累积和为0.5的位置
diversity = diversity.unstack('sex')
diversity.plot(title='Number of popular names in top 50%')
get_last_letter = lambda x:x[-1]
last_letters = names.name.map(get_last_letter)
last_letters.name = 'last_letter'
# 从name列提取最后一个字母
table = names.pivot_table('births',index=last_letters,columns=['sex','year'],aggfunc=sum)
subtable = table.reindex(columns=[1910,1960,2015],level='year')
letter_prop = subtable/subtable.sum()
fig,axes = plt.subplots(2,1,figsize=(12,10))
letter_prop['M'].plot(kind='bar',rot=0,ax=axes[0],title='Male')
letter_prop['F'].plot(kind='bar',rot=0,ax=axes[1],title='Female',legend=False)
letter_prop = table/table.sum()
dny_ts = letter_prop.loc[['d','n','y'],'M'].T
dny_ts.plot()
all_names = pd.Series(top1000.name.unique())
lesley_like = all_names[all_names.str.lower().str.contains('lesl')]
filtered = top1000[top1000.name.isin(lesley_like)]
table = filtered.pivot_table('births',index='year',columns='sex',aggfunc=sum)
table = table.div(table.sum(1),axis=0)
table.plot(style={'M':'k-','F':'k--'})
数据源链接
提取码:7pkh