-
分析了2020.7.22-2020.8.20期间75w+条捐赠数据,揭秘美国选民对总统候选人的喜好
-
利用pandas, matplotlib, wordcloud第三方库
一、前言
1.1 候选人信息(weball20.txt)
CAND_ID 候选人ID
CAND_NAME 候选人姓名
CAND_PTY_AFFILIATION 候选人党派
1.2 候选人委员会信息(ccl.txt)
CAND_ID 候选人ID
CAND_ELECTION_YR 候选人选举年份
CMTE_ID 委员会ID
1.3 个人捐款档案信息(itcont.txt)
CMTE_ID 委员会ID
NAME 捐款人姓名
CITY 捐款人所在市
State 捐款人所在州
EMPLOYER 捐款人雇主/公司
OCCUPATION 捐款人职业
1.4 需要提前安装包
# 安装词云处理包wordcloud
!pip install wordcloud --user
1.5提前下载的数据集
在进行数据处理前,你需要点击DSW左侧天池
tab,下载本案例数据集2020_US_President_political_contributions
。
二、数据处理
想分析候选人与捐赠人之间的关系,所以我们想要一张数据表中有捐赠人与候选人一一对应的关系。
2.1 委员会和候选人对应CAND_ID关联两个表
import pandas as pd
# 读取候选人信息,由于原始数据没有表头,需要添加表头
candidates = pd.read_csv("weball20.txt", sep = '|',names=['CAND_ID','CAND_NAME','CAND_ICI','PTY_CD','CAND_PTY_AFFILIATION','TTL_RECEIPTS', 'TRANS_FROM_AUTH','TTL_DISB','TRANS_TO_AUTH','COH_BOP','COH_COP','CAND_CONTRIB', 'CAND_LOANS','OTHER_LOANS','CAND_LOAN_REPAY','OTHER_LOAN_REPAY','DEBTS_OWED_BY',
'TTL_INDIV_CONTRIB','CAND_OFFICE_ST','CAND_OFFICE_DISTRICT','SPEC_ELECTION','PRIM_ELECTION','RUN_ELECTION'
,'GEN_ELECTION','GEN_ELECTION_PRECENT','OTHER_POL_CMTE_CONTRIB','POL_PTY_CONTRIB',
'CVG_END_DT','INDIV_REFUNDS','CMTE_REFUNDS'])
# 读取候选人和委员会的联系信息
ccl = pd.read_csv("ccl.txt", sep = '|',names=['CAND_ID','CAND_ELECTION_YR','FEC_ELECTION_YR','CMTE_ID','CMTE_TP','CMTE_DSGN','LINKAGE_ID'])
# 关联两个表数据
ccl = pd.merge(ccl,candidates)
# 提取出所需要的列
ccl = pd.DataFrame(ccl, columns=[ 'CMTE_ID','CAND_ID', 'CAND_NAME','CAND_PTY_AFFILIATION'])
# 查看目前ccl数据前10行
ccl.head(10)
CMTE_ID | CAND_ID | CAND_NAME | CAND_PTY_AFFILIATION | |
---|---|---|---|---|
0 | C00697789 | H0AL01055 | CARL, JERRY LEE, JR | REP |
1 | C00701557 | H0AL01063 | LAMBERT, DOUGLAS WESTLEY III | REP |
2 | C00701409 | H0AL01071 | PRINGLE, CHRISTOPHER PAUL | REP |
3 | C00703066 | H0AL01089 | HIGHTOWER, BILL | REP |
4 | C00708867 | H0AL01097 | AVERHART, JAMES | DEM |
5 | C00710947 | H0AL01105 | GARDNER, KIANI A | DEM |
6 | C00722512 | H0AL01121 | CASTORANI, JOHN | REP |
7 | C00725069 | H0AL01139 | COLLINS, FREDERICK G. RICK’ | DEM |
8 | C00462143 | H0AL02087 | ROBY, MARTHA | REP |
9 | C00493783 | H0AL02087 | ROBY, MARTHA | REP |
2.2 将候选人和捐赠人一一对应,通过CMTE_ID关联两个表
# 读取个人捐赠数据,由于原始数据没有表头,需要添加表头
# 提示:读取本文件大概需要5-10s
itcont = pd.read_csv('itcont_2020_20200722_20200820.txt', sep='|',names=['CMTE_ID','AMNDT_IND','RPT_TP','TRANSACTION_PGI', 'IMAGE_NUM','TRANSACTION_TP','ENTITY_TP','NAME','CITY',
'STATE','ZIP_CODE','EMPLOYER','OCCUPATION','TRANSACTION_DT', 'TRANSACTION_AMT','OTHER_ID','TRAN_ID','FILE_NUM','MEMO_CD',
'MEMO_TEXT','SUB_ID'])
# 将候选人与委员会关系表ccl和个人捐赠数据表itcont合并,通过 CMTE_ID
c_itcont = pd.merge(ccl,itcont)
# 提取需要的数据列
c_itcont = pd.DataFrame(c_itcont, columns=[ 'CAND_NAME','NAME', 'STATE','EMPLOYER','OCCUPATION',
'TRANSACTION_AMT', 'TRANSACTION_DT','CAND_PTY_AFFILIATION'])
# 查看目前数据前10行
c_itcont.head(10)
CAND_NAME | NAME | STATE | EMPLOYER | OCCUPATION | TRANSACTION_AMT | TRANSACTION_DT | CAND_PTY_AFFILIATION | |
---|---|---|---|---|---|---|---|---|
0 | MORGAN, JOSEPH DAVID | MARTIN, WILLIAM II | AZ | RETIRED | RETIRED | 100 | 7242020 | REP |
1 | MORGAN, JOSEPH DAVID | RODRIGUEZ, GERARDO | AZ | VA HOSPITAL | LAB TECH | 40 | 7242020 | REP |
2 | MORGAN, JOSEPH DAVID | RODRIGUEZ, GERARDO | AZ | VA HOSPITAL | LAB TECH | 40 | 7312020 | REP |
3 | WOOD, DANIEL | HOPKINS, RICHARD | AZ | POWERS-LEAVITT | INSURANCE AGENT | 300 | 8102020 | REP |
4 | WOOD, DANIEL | PENDLETON, DIANE | AZ | UNEMPLOYED | NaN | 500 | 8072020 | REP |
5 | WOOD, DANIEL | PREVATT, WILLIAM | AZ | SELF-EMPLOYED | DVM | 500 | 7312020 | REP |
6 | WOOD, DANIEL | HARDING, DOUG | AZ | MICROSURE | OPERATIONS MANAGER | 2800 | 8102020 | REP |
7 | WOOD, DANIEL | HARDING, MARI | AZ | NaN | NaN | 1400 | 8152020 | REP |
8 | WOOD, DANIEL | HEDGER, CYNTHIA | TX | NaN | NaN | 200 | 7312020 | REP |
9 | HUANG, PEGGY | HUANG - PERSONAL FUNDS, PEGGY | CA | OFFICE OF THE ATTORNEY GENERAL | DEPUTY ATTORNEY GENERAL | 2600 | 7252020 |
2.3数据探索与清理
# 查看数据规模 多少行 多少列
c_itcont.shape #(756205, 8)
# 查看整体数据信息,包括每个字段的名称、非空数量、字段的数据类型
c_itcont.info() #占内存51.9MB
#空值处理,统一填充 NOT PROVIDED
c_itcont['STATE'].fillna('NOT PROVIDED',inplace=True)
c_itcont['EMPLOYER'].fillna('NOT PROVIDED',inplace=True)
c_itcont['OCCUPATION'].fillna('NOT PROVIDED',inplace=True)
# 对日期TRANSACTION_DT列进行处理
c_itcont['TRANSACTION_DT'] = c_itcont['TRANSACTION_DT'] .astype(str)
# 将日期格式改为年月日 7242020
c_itcont['TRANSACTION_DT'] = [i[3:7]+i[0]+i[1:3] for i in c_itcont['TRANSACTION_DT'] ]
# 再次查看数据信息
c_itcont.info()
# 查看数据前3行
c_itcont.head(3)
CAND_NAME | NAME | STATE | EMPLOYER | OCCUPATION | TRANSACTION_AMT | TRANSACTION_DT | CAND_PTY_AFFILIATION | |
---|---|---|---|---|---|---|---|---|
0 | MORGAN, JOSEPH DAVID | MARTIN, WILLIAM II | AZ | RETIRED | RETIRED | 100 | 2020724 | REP |
1 | MORGAN, JOSEPH DAVID | RODRIGUEZ, GERARDO | AZ | VA HOSPITAL | LAB TECH | 40 | 2020724 | REP |
2 | MORGAN, JOSEPH DAVID | RODRIGUEZ, GERARDO | AZ | VA HOSPITAL | LAB TECH | 40 | 2020731 | REP |
# 查看数据表中数据类型的列的数据分布情况
c_itcont.describe()
TRANSACTION_AMT | |
---|---|
count | 7.562050e+05 |
mean | 1.504307e+02 |
std | 2.320452e+03 |
min | -5.600000e+03 |
25% | 2.000000e+01 |
50% | 3.500000e+01 |
75% | 1.000000e+02 |
max | 1.500000e+06 |
# 查看单列的数据发布情况
c_itcont['CAND_NAME'].describe()
count 756205
,unique 312
,top BIDEN, JOSEPH R JR
,freq 507816
,Name: CAND_NAME, dtype: object
2.4 数据分析
# 计算每个党派的所获得的捐款总额,然后排序,取前十位
c_itcont.groupby("CAND_PTY_AFFILIATION").sum().sort_values("TRANSACTION_AMT",ascending=False).head(10)
TRANSACTION_AMT | |
---|---|
CAND_PTY_AFFILIATION | |
DEM | 75961730 |
REP | 37170653 |
IND | 328802 |
LIB | 169202 |
DFL | 76825 |
GRE | 18607 |
NON | 11256 |
UNK | 10195 |
CON | 4117 |
BDY | 3250 |
# 计算每个总统候选人所获得的捐款总额,然后排序,取前十位
c_itcont.groupby("CAND_NAME").sum().sort_values("TRANSACTION_AMT",ascending=False).head(10)
TRANSACTION_AMT | |
---|---|
CAND_NAME | |
BIDEN, JOSEPH R JR | 68111142 |
TRUMP, DONALD J. | 16594982 |
SULLIVAN, DAN | 9912465 |
JACOBS, CHRISTOPHER L. | 6939209 |
BLOOMBERG, MICHAEL R. | 3451916 |
MARKEY, EDWARD J. SEN. | 606832 |
SHAHEEN, JEANNE | 505446 |
KENNEDY, JOSEPH P III | 467738 |
CORNYN, JOHN SEN | 345959 |
FIGLESTHALER, WILLIAM MATTHEW MD | 258221 |
4、数据分析
# 计算每个党派的所获得的捐款总额,然后排序,取前十位
c_itcont.groupby("CAND_PTY_AFFILIATION").sum().sort_values("TRANSACTION_AMT",ascending=False).head(10)
TRANSACTION_AMT | |
---|---|
CAND_PTY_AFFILIATION | |
DEM | 75961730 |
REP | 37170653 |
IND | 328802 |
LIB | 169202 |
DFL | 76825 |
GRE | 18607 |
NON | 11256 |
UNK | 10195 |
CON | 4117 |
BDY | 3250 |
# 计算每个总统候选人所获得的捐款总额,然后排序,取前十位
c_itcont.groupby("CAND_NAME").sum().sort_values("TRANSACTION_AMT",ascending=False).head(10)
TRANSACTION_AMT | |
---|---|
CAND_NAME | |
BIDEN, JOSEPH R JR | 68111142 |
TRUMP, DONALD J. | 16594982 |
SULLIVAN, DAN | 9912465 |
JACOBS, CHRISTOPHER L. | 6939209 |
BLOOMBERG, MICHAEL R. | 3451916 |
MARKEY, EDWARD J. SEN. | 606832 |
SHAHEEN, JEANNE | 505446 |
KENNEDY, JOSEPH P III | 467738 |
CORNYN, JOHN SEN | 345959 |
FIGLESTHALER, WILLIAM MATTHEW MD | 258221 |
获得捐赠最多的党派有DEM(民主党)
、REP(共和党)
,分别对应BIDEN, JOSEPH R JR(拜登)
和TRUMP, DONALD J.(特朗普)
。
# 查看每个州捐款人的数量
c_itcont['STATE'].value_counts().head(5)
CA 127895
,TX 54457
,FL 54343
,NY 49453
,MA 29314
,Name: STATE, dtype: int64
CA(加利福利亚)
、NY(纽约)
、FL(弗罗里达)
这几个州的捐款是最多的
三、数据可视化
3.1 按州总捐款数和总捐款数柱状图
导入相关库
# 导入matplotlib中的pyplot
import matplotlib.pyplot as plt
# 为了使matplotlib图形能够内联显示
%matplotlib inline
# 导入词云库
from wordcloud import WordCloud,ImageColorGenerator
# 各州总捐款数可视化
st_amt = c_itcont.groupby('STATE').sum().sort_values("TRANSACTION_AMT",ascending=False)[:10]
st_amt=pd.DataFrame(st_amt, columns=['TRANSACTION_AMT'])
st_amt.plot(kind='bar')
3.2 各州捐款总人数可视化
# 各州捐款总人数可视化,取前10个州的数据
st_amt = c_itcont.groupby('STATE').size().sort_values(ascending=False).head(10)
st_amt.plot(kind='bar')
3.3 热门候选人拜登在各州的获得的捐赠占比
# 从所有数据中取出支持拜登的数据
biden = c_itcont[c_itcont['CAND_NAME']=='BIDEN, JOSEPH R JR']
# 统计各州对拜登的捐款总数
biden_state = biden.groupby('STATE').sum().sort_values("TRANSACTION_AMT", ascending=False).head(10)
# 饼图可视化各州捐款数据占比
biden_state.plot.pie(figsize=(10, 10),autopct='%0.2f%%',subplots=True)
3.4总捐款最多的候选人捐赠者词云图
https://img.alicdn.com/tfs/TB10Jx4pBBh1e4jSZFhXXcC9VXa-689-390.jpg
# 由于下载图片文件名过长,我们对文件名进行重命名
import os
os.rename('TB10Jx4pBBh1e4jSZFhXXcC9VXa-689-390.jpg', 'biden.jpg')
# 在4.2 热门候选人拜登在各州的获得的捐赠占比 中我们已经取出了所有支持拜登的人的数据,存在变量:biden中
# 将所有捐赠者姓名连接成一个字符串
data = ' '.join(biden["NAME"].tolist())
# 读取图片文件
bg = plt.imread("biden.jpg")
# 生成
wc = WordCloud(# FFFAE3
background_color="white", # 设置背景为白色,默认为黑色
width=890, # 设置图片的宽度
height=600, # 设置图片的高度
mask=bg, # 画布
margin=10, # 设置图片的边缘
max_font_size=100, # 显示的最大的字体大小
random_state=20, # 为每个单词返回一个PIL颜色
).generate_from_text(data)
# 图片背景
bg_color = ImageColorGenerator(bg)
# 开始画图
plt.imshow(wc.recolor(color_func=bg_color))
# 为云图去掉坐标轴
plt.axis("off")
# 画云图,显示
# 保存云图
wc.to_file("biden_wordcloud.png")