需求:
- 導入文件,查看原始數據
- 將人口數據和各州簡稱數據進行合並
- 將合並的數據中重復的abbreviation列進行刪除
- 查看存在缺失數據的列
- 找到有哪些state/region使得state的值為NaN,進行去重操作
- 為找到的這些state/region的state項補上正確的值,從而去除掉state這一列的所有NaN
- 合並各州面積數據areas
- 我們會發現area(sq.mi)這一列有缺失數據,找出是哪些行
- 去除含有缺失數據的行
- 找出2010年的全民人口數據
- 計算各州的人口密度
- 排序,並找出人口密度最高的五個州 df.sort_values()
import numpy as np from pandas import DataFrame,Series import pandas as pd
abb = pd.read_csv('./data/state-abbrevs.csv') pop = pd.read_csv('./data/state-population.csv') area = pd.read_csv('./data/state-areas.csv')
#將人口數據和各州簡稱數據進行合並 display(abb.head(1),pop.head(1)) abb_pop = pd.merge(abb,pop,left_on='abbreviation',right_on='state/region',how='outer') abb_pop.head()
#將合並的數據中重復的abbreviation列進行刪除 abb_pop.drop(labels='abbreviation',axis=1,inplace=True) abb_pop.head()
| state | state/region | ages | year | population | |
|---|---|---|---|---|---|
| 0 | Alabama | AL | under18 | 2012 | 1117489.0 |
| 1 | Alabama | AL | total | 2012 | 4817528.0 |
| 2 | Alabama | AL | under18 | 2010 | 1130966.0 |
| 3 | Alabama | AL | total | 2010 | 4785570.0 |
| 4 | Alabama | AL | under18 | 2011 | 1125763.0 |
#查看存在缺失數據的列 abb_pop.isnull().any(axis=0)
state True state/region False ages False year False population True dtype: bool
#找到有哪些state/region使得state的值為NaN,進行去重操作 #1.檢測state列中的空值 abb_pop['state'].isnull()
#2.將1的返回值作用的state_region這一列中 abb_pop['state/region'][abb_pop['state'].isnull()]
#3.去重 abb_pop['state/region'][abb_pop['state'].isnull()].unique()
#為找到的這些state/region的state項補上正確的值,從而去除掉state這一列的所有NaN abb_pop['state/region'] == 'USA'
indexs = abb_pop['state'][abb_pop['state/region'] == 'USA'].index abb_pop.loc[indexs,'state'] = 'United State' pr_index = abb_pop['state'][abb_pop['state/region'] == 'PR'].index abb_pop.loc[pr_index,'state'] = 'PPPRRR'
合並各州面積數據areas 我們會發現area(sq.mi)這一列有缺失數據,找出是哪些行 去除含有缺失數據的行 找出2010年的全民人口數據 計算各州的人口密度 排序,並找出人口密度最高的五個州 df.sort_values()
#合並各州面積數據areas abb_pop_area = pd.merge(abb_pop,area,how='outer') abb_pop_area.head()
#我們會發現area(sq.mi)這一列有缺失數據,找出是哪些行 abb_pop_area['area (sq. mi)'].isnull()
a_index = abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()].index
#去除含有缺失數據的行 abb_pop_area.drop(labels=a_index,axis=0,inplace=True) #找出2010年的全民人口數據 abb_pop_area.query('year == 2010 & ages == "total"') #計算各州的人口密度 abb_pop_area['midu'] = abb_pop_area['population'] / abb_pop_area['area (sq. mi)'] abb_pop_area.head()
#排序,並找出人口密度最高的五個州 df.sort_values() abb_pop_area.sort_values(by='midu',axis=0,ascending=False).head()
