python数据分析实践(三)

All Time Olympic Games Medals

处理维基百科 All Time Olympic Games Medals 数据集。

import pandas as pd
# 读取数据,选取第一列作为index,并跳过第一行,以第二行作为我的column name
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
# 对column进行部分重命名
for col in df.columns:
    if col[:2]=='01':
        df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
    if col[:2]=='02':
        df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
    if col[:2]=='03':
        df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
    if col[:1]=='№':
        df.rename(columns={col:'#'+col[1:]}, inplace=True)

names_ids = df.index.str.split('\s\(') # split the index by '('

df.index = names_ids.str[0] # the [0] element is the country name (new index) 
df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that)
# 删除Total列
df = df.drop('Totals')
df.head()
任务一:返回DataFrame的第一行
def answer_zero():
    return df.iloc[0]

必须使用 ilociloc 使用index进行索引, loc 使用index name进行索引。

任务二:返回夏季奥运会获得金牌数最多的国家名
def answer_one():
    return df.Gold.idxmax()

一开始考虑使用布尔量索引,df[df.Gold==df.Gold.max()].index[0] ,非常繁琐,结果我去查Series文档发现有非常直接简单的方法。采用**idxmax(), idxmin()**返回Series最大最小值的索引值。

任务三:返回夏季金牌数和冬季金牌数之差相对于总金牌数最大的国家名(只考虑在夏季冬季奥运会至少都获得过1枚金牌的国家)

夏 季 金 牌 数 − 冬 季 金 牌 数 总 金 牌 数 \frac{夏季金牌数-冬季金牌数}{总金牌数}

def answer_three():
    df1 = df[(df.Gold > 0) & (df['Gold.1'] > 0) ]
    return abs((df1['Gold.1']-df1.Gold)/df1['Gold.2']).idxmax()
任务四:返回一个名为"Points"的Series

Points = Gold.2 × 3 + Silver.2 × 2 + Bronze.2 × 1 \text{Points}=\text{Gold.2}\times 3 + \text{Silver.2}\times 2 + \text{Bronze.2}\times 1 Points=Gold.2×3+Silver.2×2+Bronze.2×1

def answer_four():
    return pd.Series(data = df['Gold.2']*3 + df['Silver.2']*2 + df['Bronze.2']*1,name='Points')

Population Data for Counties and States in the US from 2010 to 2015

处理来自 United States Census Bureau 的人口普查数据集。

import pandas as pd
census_df = pd.read_csv('census.csv')
任务一:返回拥有最多Country的State
def answer_five():
    return census_df[census_df.STNAME != census_df.CTYNAME].STNAME.value_counts().idxmax()
任务二:返回在每个State仅考虑人数最多的三个Country时的三个人数最多的State(2010)
def answer_six():
    census_df1 = census_df[census_df.STNAME != census_df.CTYNAME][['STATE','STNAME','CTYNAME','CENSUS2010POP']].set_index('STATE')
    new_df = pd.DataFrame(columns=['STATE','STNAME','CTYNAME','CENSUS2010POP'])
    for i in range(56):
        try:
            new_df = pd.concat([new_df, census_df1.loc[i+1].sort_values(by='CENSUS2010POP',ascending= False).iloc[:3].reset_index()])
        except KeyError:
            pass
    return list(new_df.groupby(['STNAME']).sum().CENSUS2010POP.sort_values(ascending= False).iloc[:3].index)
任务三:返回10-15年人数变化最大的Country
def answer_seven():
    census_df1 = census_df[census_df.STNAME != census_df.CTYNAME][['CTYNAME','POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014','POPESTIMATE2015']].set_index('CTYNAME')
    return (census_df1.max(axis=1)-census_df1.min(axis=1)).idxmax()
任务四:返回属于Region1或Region2,名字始于’Washington’且15年人数多于14年人数的Country
def answer_eight():
    return census_df[(census_df.REGION < 3) & (census_df.POPESTIMATE2015 > census_df.POPESTIMATE2014) & (census_df.CTYNAME.str[:10]=='Washington')][['STNAME','CTYNAME']]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值