需求:
- 導入文件,查看原始數據
- 將人口數據和各州簡稱數據進行合並
- 將合並的數據中重復的abbreviation列進行刪除
- 查看存在缺失數據的列
- 找到有哪些state/region使得state的值為NaN,進行去重操作
- 為找到的這些state/region的state項補上正確的值,從而去除掉state這一列的所有NaN
- 合並各州面積數據areas
- 我們會發現area(sq.mi)這一列有缺失數據,找出是哪些行
- 去除含有缺失數據的行
- 找出2010年的全民人口數據
- 計算各州的人口密度
- 排序,並找出人口密度最高的五個州 df.sort_values()
實現:
1.首先導入文件,並查看數據樣本
import numpy as np import pandas as pd from pandas import Series, DataFrame abb = pd.read_csv('../data/state-abbrevs.csv') areas = pd.read_csv('../data/state-areas.csv') pop = pd.read_csv('../data/state-population.csv')
2.將人口數據pop和各州簡稱數據abbrevs兩個DataFrame進行合並, 分別依據state/region列和abbreviation列來合並
abb_pop = pd.merge(abb, pop, how='outer', left_on='abbreviation', right_on='state/region') abb_pop.head(6)
3.將合並的數據中重復的abbreviation列進行刪除
# 刪除重復的列 abb_pop.drop(labels=['abbreviation'], axis=1, inplace=True)
4.查看存在缺失數據的列
abb_pop.isnull().any(axis=0) # 檢查每一列中是否存在空值(True) # 運行結果發現只有state和population中存在空值 abb_pop.loc[abb_pop['population'].isnull()] # 獲取了pop空值所對應的行數據 # 查看state這一列中的空值存在情況 abb_pop['state'].isnull() # 如果該列中某一個數組元素為空值,則顯示True # 將上一步返回的布爾列表作為行索引 state=abb_pop.loc[abb_pop['state'].isnull()] state
5.找到有哪些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() # unique()是Serise的一個函數,該函數可以對Serise中的數組元素進行去重
6.為找到的這些state/region的state項補上正確的值,從而去除掉state這一列的所有NaN
# 可以通過簡稱定位到指定的state列中的空值(可以被批量賦值) abb_pop['state/region'] == 'PR' indexs = abb_pop.loc[abb_pop['state/region'] == 'PR'].index abb_pop.loc[indexs, 'state'] = 'PPPRRR' # 先定位到USA簡稱對應的全稱的空值 abb_pop['state/region'] == 'USA' abb_pop.loc[abb_pop['state/region'] == 'USA'] # 獲取的就是簡稱USA對應的行數據(state列表全部為空) indexs = abb_pop.loc[abb_pop['state/region'] == 'USA'].index abb_pop.loc[indexs, 'state'] = 'United State' # 簡寫 abb_pop.loc[abb_pop['state/region']=='PR','state']='PUERTO RICO' abb_pop.loc[abb_pop['state/region']=='USA','state']='United State'
7.合並各州面積數據areas,使用左合並。
abb_pop_area = pd.merge(abb_pop, areas, how='left')
8.我們會發現area(sq.mi)這一列有缺失數據,找出是哪些行
abb_pop_area.isnull().any(axis=0) # 尋找存在缺失數據的列 abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()] # 獲取行索引 indexs=abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()].index
9.去除含有缺失數據的行
abb_pop_area.drop(indexs,axis=0,inplace=True)
10.找出2010年的全民人口數據,df.query(查詢語句)
data_2010 = abb_pop_area.query("year==2010 & ages=='total'")
11.計算人口密度。注意是Series/Series,其結果還是一個Series。
data_2010_index['midu'] = data_2010_index['population'] / data_2010_index['area (sq. mi)']
12.排序,並找出人口密度最高的五個州sort_values()
data_2010_index.sort_values(by='midu',axis=0,ascending=False).head()
要點總結:
- 統一用loc()索引
- 善於使用.isnull().any()找到存在NaN的列
- 善於使用.unique()確定該列中哪些key是我們需要的
- 一般使用外合並、左合並,目的只有一個:寧願該列是NaN也不要丟棄其他列的信息