Python数据分析-人口分析案例、2012美国大选献金项目数据分析

人口分析案例

需求:

  • 导入文件,查看原始数据
  • 将人口数据和各州简称数据进行合并
  • 将合并的数据中重复的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 numpy as 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.drop(labels='abbreviation',axis=1,inplace=True)

#查看存在缺失数据的列
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)

 2012美国大选献金项目数据分析

需求

  • 加载数据
  • 查看数据的基本信息
  • 指定数据截取,将如下字段的数据进行提取,其他数据舍弃
    • cand_nm :候选人姓名
    • contbr_nm : 捐赠人姓名
    • contbr_st :捐赠人所在州
    • contbr_employer : 捐赠人所在公司
    • contbr_occupation : 捐赠人职业
    • contb_receipt_amt :捐赠数额(美元)
    • contb_receipt_dt : 捐款的日期
  • 对新数据进行总览,查看是否存在缺失数据
  • 用统计学指标快速描述数值型属性的概要。
  • 空值处理。可能因为忘记填写或者保密等等原因,相关字段出现了空值,将其填充为NOT PROVIDE
  • 异常值处理。将捐款金额<=0的数据删除
  • 新建一列为各个候选人所在党派party
  • 查看party这一列中有哪些不同的元素
  • 统计party列中各个元素出现次数
  • 查看各个党派收到的政治献金总数contb_receipt_amt
  • 查看具体每天各个党派收到的政治献金总数contb_receipt_amt
  • 将表中日期格式转换为'yyyy-mm-dd'。
  • 查看老兵(捐献者职业)DISABLED VETERAN主要支持谁

import numpy as np
import pandas as pd
#方便操作,将月份和参选人以及所在政党进行定义:
months = {'JAN' : 1, 'FEB' : 2, 'MAR' : 3, 'APR' : 4, 'MAY' : 5, 'JUN' : 6,
'JUL' : 7, 'AUG' : 8, 'SEP' : 9, 'OCT': 10, 'NOV': 11, 'DEC' : 12}
of_interest = ['Obama, Barack', 'Romney, Mitt', 'Santorum, Rick',
'Paul, Ron', 'Gingrich, Newt']
parties = {
'Bachmann, Michelle': 'Republican',
'Romney, Mitt': 'Republican',
'Obama, Barack': 'Democrat',
"Roemer, Charles E. 'Buddy' III": 'Reform',
'Pawlenty, Timothy': 'Republican',
'Johnson, Gary Earl': 'Libertarian',
'Paul, Ron': 'Republican',
'Santorum, Rick': 'Republican',
'Cain, Herman': 'Republican',
'Gingrich, Newt': 'Republican',
'McCotter, Thaddeus G': 'Republican',
'Huntsman, Jon': 'Republican',
'Perry, Rick': 'Republican'
}

df = pd.read_csv('./data/usa_election.txt')
df.head()

 

 df.shape

(536041, 16)

#对新数据进行总览,查看是否存在缺失数据
df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 536041 entries, 0 to 536040
Data columns (total 16 columns):
cmte_id              536041 non-null object
cand_id              536041 non-null object
cand_nm              536041 non-null object
contbr_nm            536041 non-null object
contbr_city          536026 non-null object
contbr_st            536040 non-null object
contbr_zip           535973 non-null object
contbr_employer      525088 non-null object
contbr_occupation    530520 non-null object
contb_receipt_amt    536041 non-null float64
contb_receipt_dt     536041 non-null object
receipt_desc         8479 non-null object
memo_cd              49718 non-null object
memo_text            52740 non-null object
form_tp              536041 non-null object
file_num             536041 non-null int64
dtypes: float64(1), int64(1), object(14)
memory usage: 65.4+ MB

df.describe() #对原始数据数值型数据的统计描述

 

 #空值处理。可能因为忘记填写或者保密等等原因,相关字段出现了空值,将其填充为NOT PROVIDE

df.fillna(value='NOT PROVIDE',inplace=True)

#异常值处理。将捐款金额<=0的数据删除
df = df.loc[~(df['contb_receipt_amt'] <= 0)]

#新建一列为各个候选人所在党派party
df['party'] = df['cand_nm'].map(parties)
df.head()

 

 

#查看party这一列中有哪些不同的元素
df['party'].unique()

array(['Republican', 'Democrat', 'Reform', 'Libertarian'], dtype=object)

#统计party列中各个元素出现次数
df['party'].value_counts()

Democrat       289999
Republican     234300
Reform           5313
Libertarian       702
Name: party, dtype: int64

#查看各个党派收到的政治献金总数contb_receipt_amt
df.groupby(by='party')['contb_receipt_amt'].sum()

party
Democrat       8.259441e+07
Libertarian    4.132769e+05
Reform         3.429658e+05
Republican     1.251181e+08
Name: contb_receipt_amt, dtype: float64

#查看具体每天各个党派收到的政治献金总数contb_receipt_amt
df.groupby(by=['contb_receipt_dt','party'])['contb_receipt_amt'].sum()

 

 

#将表中日期格式转换为'yyyy-mm-dd'。
def transform_date(d):
day,month,year = d.split('-')
month = months[month]
return '20'+year+'-'+str(month)+'-'+day
# df['contb_receipt_dt'].map(transform_date)
df['contb_receipt_dt'] = df['contb_receipt_dt'].apply(transform_date)
df.head()

 

 

 

#查看老兵(捐献者职业)DISABLED VETERAN主要支持谁
#老兵给谁捐的钱最多就表示最支持谁

#1.将老兵对应的行数据
old_bing_df = df.loc[df['contbr_occupation'] == 'DISABLED VETERAN']

#2.根据候选人分组
old_bing_df.groupby(by='cand_nm')['contb_receipt_amt'].sum()

cand_nm
Cain, Herman       300.00
Obama, Barack     4205.00
Paul, Ron         2425.49
Santorum, Rick     250.00
Name: contb_receipt_amt, dtype: float64

 

posted @ 2020-07-15 21:01  闲酒肆中听风吟  阅读(493)  评论(0)    收藏  举报