人口分析案例
需求:
- 匯入檔案,檢視原始資料
- 將人口資料和各州簡稱資料進行合併
- 將合併的資料中重複的abbreviation列進行刪除
- 檢視存在缺失資料的列
- 找到有哪些state/region使得state的值為NaN,進行去重操作
- 為找到的這些state/region的state項補上正確的值,從而去除掉state這一列的所有NaN
- 合併各州面積資料areas
- 我們會發現area(sq.mi)這一列有缺失資料,找出是哪些行
- 去除含有缺失資料的行
- 找出2010年的全民人口資料
- 計算各州的人口密度
- 排序,並找出人口密度最高的州
import pandas as pd from pandas import DataFrame,Series import numpyas np abb = pd.read_csv('./data/state-abbrevs.csv') abb.head() #state州的全稱 #abbreviation州的簡稱
pop = pd.read_csv('./data/state-population.csv')
pop.head()
#將abb和pop進行資料的合併
abb_pop = pd.merge(left=abb,right=pop,left_on='abbreviation',right_on='state/region',how='outer')
abb_pop.head()
#將合併的資料中重複的abbreviation列進行刪除
#檢視存在缺失資料的列
abb_pop.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 2544 entries, 0 to 2543 Data columns (total 5 columns): state 2448 non-null object state/region 2544 non-null object ages 2544 non-null object year 2544 non-null int64 population 2524 non-null float64 dtypes: float64(1), int64(1), object(3) memory usage: 119.2+ KB
abb_pop.isnull().any(axis=0)
state True state/region False ages False year False population True dtype: bool
#ages列中存有哪些不同的元素
abb_pop['ages'].unique()
array(['under18', 'total'], dtype=object)
#檢視ages列中不同元素出現的次數
abb_pop['ages'].value_counts()
total 1272 under18 1272 Name: ages, dtype: int64
#找到有哪些state/region使得state的值為NaN,進行去重操作
#前提:已知state列中存有空值資料
#將state列中的空值對應的簡稱資料找出,且對這些找出的簡稱資料進行去重,去重後就可以得知
#到底是哪些簡稱對應的全稱的值為空
abb_pop.head()
#1.將state中的空值找出
abb_pop['state'].isnull()
#2.將步驟1獲取的布林值作為源資料的行索引,獲得state為空值對應的行資料
abb_pop.loc[abb_pop['state'].isnull()]
#3.將步驟二獲取的df中的簡稱列取出即可
abb_pop.loc[abb_pop['state'].isnull()]['state/region']
#4.去重
abb_pop.loc[abb_pop['state'].isnull()]['state/region'].unique()
#為找到的這些state/region的state項補上正確的值,從而去除掉state這一列的所有NaN
#分析:
#state列出現的空值依次可以被填充為PR和USA的全稱
#將state列中對應PR的空資料取出,給其填充成PR的全稱
#將state列中對應USA的空資料取出,給其填充成USA的全稱
#1.將PR對應的行資料取出
abb_pop['state/region'] == 'PR'
abb_pop.loc[abb_pop['state/region'] == 'PR']
#2.可以將上一步獲取的臨時表的行索引獲取
#行索引就是PR對應的空值對應的行索引
indexs = abb_pop.loc[abb_pop['state/region'] == 'PR'].index
#3.填充
abb_pop.loc[indexs,'state'] = 'PPPRRR'
#1.將USA對應的行資料取出
abb_pop['state/region'] == 'USA'
abb_pop.loc[abb_pop['state/region'] == 'USA']
#2.獲取需要填充空值的索引
indexs = abb_pop.loc[abb_pop['state/region'] == 'USA'].index
#3.填充
abb_pop.loc[indexs,'state'] = 'United States'
#合併各州面積資料areas
abb_pop_area = pd.merge(left=abb_pop,right=area,on='state',how='outer')
abb_pop_area.head()
#我們會發現area(sq.mi)這一列有缺失資料,找出是哪些行
drop_indexs = abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()].index
#去除含有缺失資料的行
abb_pop_area.drop(labels=drop_indexs,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.sort_values(by='midu',axis=0,ascending=False)