1. 程式人生 > >資料分析案例_2012聯邦選舉資料分析

資料分析案例_2012聯邦選舉資料分析

展示一份資料分析案例解說,主要是用於說明資料分析過程。大致過程是先讀取資料為DataFrame格式,利用pandas處理需要的行或列,再用畫圖展示出來。

#2012 美國聯邦選舉資料分析 案例'''
該分析案例摘自經典資料分析書籍《利用Python進行資料分析》,本文主要是對該案例進行解說。
案例的資料來源檔案為150MBCSV檔案 包含了贊助者的姓名、職業、僱主、地址及出資金額等
該案例主要分析了職業和僱主的贊助資訊,出資額分組,以及按州統計贊助資訊(地圖顯示功能未實現)
使用知識點read_csv檔案讀取,pandas資料處理,groupby分組和matplotlib的畫圖'''
#程式碼及解說
import pandas as pd import numpy as np import matplotlib.pyplot as plt #讀取原始檔的資料 origData = pd.read_csv('data/voting_data_2012.csv') v_data = origData # print('Check data size:',np.shape(v_data)) #因原始資料中沒有黨派資訊,給資料增加一列黨派資訊 unique_cands = v_data.cand_nm.unique() parties = {'Bachmann, Michelle': 'Republican'
, 'Cain, Herman': 'Republican', 'Gingrich, Newt': 'Republican', 'Huntsman, Jon': 'Republican', 'Johnson, Gary Earl': 'Republican', 'McCotter, Thaddeus G': 'Republican', 'Obama, Barack': 'Democrat', 'Paul, Ron': 'Republican'
, 'Pawlenty, Timothy': 'Republican', 'Perry, Rick': 'Republican', "Roemer, Charles E. 'Buddy' III": 'Republican', 'Romney, Mitt': 'Republican', 'Santorum, Rick': 'Republican'} v_data['party'] = v_data.cand_nm.map(parties) # print (v_data['party'].value_counts()) # 優化資料保留出資額為正的資料, 並建立一個只保留兩位主要競選人的子集 v_data = v_data[v_data.contb_receipt_amt>0] v_data_mrbo = v_data[v_data.cand_nm.isin(['Obama, Barack', 'Romney, Mitt'])] #根據職業和僱主統計贊助資訊進行分析 # 對職業和僱主資訊進行處理,清理名稱相同或多種變體的形式, 採用字典dict.get()進行處理 occ_mapping = { 'INFORMATION REQUESTED PER BEST EFFORTS' : 'NOT PROVIDED', 'INFORMATION REQUESTED' : 'NOT PROVIDED', 'INFORMATION REQUESTED (BEST EFFORTS)' : 'NOT PROVIDED', 'C.E.O.': 'CEO' } emp_mapping = { 'INFORMATION REQUESTED PER BEST EFFORTS' : 'NOT PROVIDED', 'INFORMATION REQUESTED' : 'NOT PROVIDED', 'SELF' : 'SELF-EMPLOYED', 'SELF EMPLOYED' : 'SELF-EMPLOYED', } # 如果清理過程中沒有找到相應的對映則返回x f_occ = lambda x: occ_mapping.get(x,x) v_data.contbr_occupation = v_data.contbr_occupation.map(f_occ) f_emp = lambda x: emp_mapping.get(x,x) v_data.contbr_employer = v_data.contbr_employer.map(f_emp) by_occupation = v_data.pivot_table('contb_receipt_amt', index='contbr_occupation', columns='party', aggfunc='sum') #過濾資金小於200萬的資料, 並把 200萬以上畫圖顯示出來 over_2m = by_occupation[by_occupation.sum(1) > 2000000] # print ('Sponsor more than 2M', over_2m) over_2m.plot(kind='barh') #構建一個函式計算出資額最高的企業和職業 def get_top_amounts(group, key, n=5): totals = group.groupby(key)['contb_receipt_amt'].sum() # return totals.order(ascending=False)[-n:] 原文該語句過時 採用下面語句代替 return sorted(totals,reverse=True)[:n] # 按職業和僱主進行聚合 然後找出職業排名前7項和 僱主排名前10grouped = v_data_mrbo.groupby('cand_nm') show_occ = grouped.apply(get_top_amounts, 'contbr_occupation', n=7) show_emp = grouped.apply(get_top_amounts,'contbr_employer', n=10) # print ('Top occupation',show_occ) # print ('Top employer',show_emp) #對出資額的進行分組 # 資金額度等級劃分 bins = np.array([0,1,10,100,1000,10000,100000,1000000,10000000]) labels = pd.cut(v_data_mrbo.contb_receipt_amt, bins) grouped = v_data_mrbo.groupby(['cand_nm',labels]) grouped_show = grouped.size().unstack(0) # print (grouped_show) #對出資額求和在面元內規格化 並畫圖 bucket_sum = grouped.contb_receipt_amt.sum().unstack(0) normed_sum = bucket_sum.div(bucket_sum.sum(axis=1), axis=0) normed_sum[:-2].plot(kind='barh', stacked=True) #根據州統計贊助資訊 # 獲取贊助超過100000的贊助者 grouped = v_data_mrbo.groupby(['cand_nm','contbr_st']) totals = grouped.contb_receipt_amt.sum().unstack(0).fillna(0) totals = totals[totals.sum(1)>100000] #各候選人在各州與總贊助額比例 percent = totals.div(totals.sum(1), axis=0) print(percent) plt.show()