python数据分析
读取文件
import pandas as pd
noble=pd.read_csv(‘nobel.csv’)
head参数是显示多少行数据
noble.head()
统计得奖国家最多的是
value_counts()对数据进行分组求和
noble[‘birth_country’].value_counts().head(10)
需要增加一列数据,标记美国获得者为true
noble[‘usa_winner’]=noble[‘birth_country’]==‘United States of America’
读取年份,按照10年为一组
noble[‘decade’]=noble[‘year’]//10*10
对数据进行分组
分组groupby(‘建立群组’)[对哪个对象进行分组,要查询的对象]要做什么
as_index=False 保留原有的列名
prop_usa_winner=noble.groupby(‘decade’,as_index=False)[‘usa_winner’].sum()
prop_usa_winner
可视化
import matplotlib.pyplot as plt
设置画布大小
plt.rcParams[‘figure.figsize’]=[11,7]
plt.plot(prop_usa_winner[‘decade’],prop_usa_winner[‘usa_winner’])
找出诺贝尔女性比例
取出所有诺贝尔女性得住
计算所占比例
计算第一位女性诺贝尔奖得住是哪一年得奖的
noble[‘sex’].value_counts()
计算女性得住年份
新增一列,女性为true,男性为false
noble[‘Female_winner’]=noble[‘sex’]==‘Female’
对数据以10年分组进行求和
prop_Female_winner=noble.groupby(‘decade’,as_index=False)[‘Female_winner’].sum()
prop_Female_winner
plt.plot(prop_Female_winner[‘decade’],prop_Female_winner[‘Female_winner’])
筛选条件,女,1个人,一个女人获得标记为true
noble[‘Female_winner_onlyone’]=(noble[‘sex’]‘Female’)&(noble[‘prize_share’]‘1/1’)
以10年分组,求和
prop_Femal_winner_only=noble.groupby(‘decade’,as_index=False)[‘Female_winner_onlyone’].sum()
prop_Femal_winner_only
plt.plot(prop_Femal_winner_only[‘decade’],prop_Femal_winner_only[‘Female_winner_onlyone’])
找出诺贝尔将的平均年龄
死亡日期-出生日期=年龄
进行可视化
日期是字符串格式,需要转换为时间格式to_datetime(需要转换的数据)
替换现有列
noble[‘birth_date’]=pd.to_datetime(noble[‘birth_date’])
转换后日期不变,格式转换为时间格式
获奖年份-出生日期=获奖年纪
出生日期.dt.year获取到出生年
noble[‘age’]=noble[‘year’]-noble[‘birth_date’].dt.year
绘制对应的散点图,x采用年份,y采用年龄
plt.scatter(noble[‘year’],noble[‘age’])
趋势分析
import seaborn as sns
sns.lmplot(data=noble,x=‘year’,y=‘age’,line_kws={‘color’:‘red’},aspect=2,lowess=True,row=‘category’)