# 美國人口普查數據分析
需求: 導入文件,查看原始數據 將人口數據和各州簡稱數據進行合並 將合並的數據中重復的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') #州面積 #將人口數據和各州簡稱數據進行合並 abb_pop = pd.merge(abb,pop,how='outer',left_on='abbreviation',right_on='state/region') abb_pop.head(1) #將合並的數據中重復的abbreviation列進行刪除 abb_pop.drop(labels='abbreviation',axis=1,inplace=True) #列 # 查看存在缺失數據的列 abb_pop.isnull().any(axis=0) # #找到有哪些state/region使得state的值為NaN,進行去重操作 indexs = abb_pop['state'][abb_pop['state'].isnull()].index abb_pop.iloc[indexs]['state/region'].unique() # 為找到的這些state/region的state項補上正確的值,從而去除掉state這一列的所有NaN indexs = abb_pop.loc[abb_pop['state/region'] == 'PR'].index abb_pop.loc[indexs,'state'] = 'PPPRRR'

#找到有哪些state/region使得state的值為NaN,進行去重操作 #1.state列中哪些值為空 abb_pop['state'].isnull() abb_pop.loc[abb_pop['state'].isnull()] #獲取了state值為空對應的行數據 #2.將state中空值對應的簡稱的數據獲取 abb_pop.loc[abb_pop['state'].isnull()]['state/region'] abb_pop.loc[abb_pop['state'].isnull()]['state/region'].unique()
# 先將USA簡稱對應的全稱定位到 abb_pop['state/region']=='USA' abb_pop.loc[abb_pop['state/region']=='USA'] indexs = abb_pop.loc[abb_pop['state/region']=='USA'].index abb_pop.loc[indexs,'state'] = 'United State' # 合並各州面積數據areas abb_pop_area = pd.merge(abb_pop,area,'outer') #可以查看head() # 去除含有缺失數據的行 abb_pop_area['area (sq. mi)'].isnull() abb_pop_area = abb_pop_area.loc[~(abb_pop_area['area (sq. mi)'].isnull())] #找出2010年的全民人口數據 abb_pop_area.query('ages == "total"&year=="2010"') # 計算各州的人口密度 midu = abb_pop_area['population']/abb_pop_area['area (sq. mi)'] abb_pop_area['midu'] = midu abb_pop_area.head() #對密度進行排序 列 acs升序 abb_pop_area.sort_values(by='midu',axis=0,ascending=False).head(5)