python数据分析基础03——练习项目

人口分析案例

  • 需求:
    • 导入文件,查看原始数据
    • 将人口数据和各州简称数据进行数据汇总
    • 将汇总的数据中重复的abbreviation列进行删除
    • 在汇总的数据中查看存在缺失数据的列
    • 在汇总的数据中找到有哪些state/region使得state的值为NaN,进行去重操作
    • 为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的所有NaN
    • 汇总的数据和各州面积数据areas进行汇总
    • 我们会发现area(sq.mi)这一列有缺失数据,找出是哪些行
    • 去除含有缺失数据的行
    • 找出2010年的全民人口数据
    • 计算各州的人口密度
import pandas as pd
import numpy as np
# state州全称 abbreviation州的简称
abb = pd.read_csv('./state-abbrevs.csv')
abb
stateabbreviation
0AlabamaAL
1AlaskaAK
2ArizonaAZ
3ArkansasAR
4CaliforniaCA
5ColoradoCO
6ConnecticutCT
7DelawareDE
8District of ColumbiaDC
9FloridaFL
10GeorgiaGA
11HawaiiHI
12IdahoID
13IllinoisIL
14IndianaIN
15IowaIA
16KansasKS
17KentuckyKY
18LouisianaLA
19MaineME
20MontanaMT
21NebraskaNE
22NevadaNV
23New HampshireNH
24New JerseyNJ
25New MexicoNM
26New YorkNY
27North CarolinaNC
28North DakotaND
29OhioOH
30OklahomaOK
31OregonOR
32MarylandMD
33MassachusettsMA
34MichiganMI
35MinnesotaMN
36MississippiMS
37MissouriMO
38PennsylvaniaPA
39Rhode IslandRI
40South CarolinaSC
41South DakotaSD
42TennesseeTN
43TexasTX
44UtahUT
45VermontVT
46VirginiaVA
47WashingtonWA
48West VirginiaWV
49WisconsinWI
50WyomingWY
#state/region:州的简称 ages:年龄 year时间  population人口数量
pop = pd.read_csv('./state-population.csv')
#state州的全称  area (sq. mi)面积
area = pd.read_csv('./state-areas.csv')
abb_pop = pd.merge(left=abb,right=pop,left_on='abbreviation',right_on='state/region',how='outer')
abb_pop
stateabbreviationstate/regionagesyearpopulation
0AlabamaALALunder1820121117489.0
1AlabamaALALtotal20124817528.0
2AlabamaALALunder1820101130966.0
3AlabamaALALtotal20104785570.0
4AlabamaALALunder1820111125763.0
.....................
2539NaNNaNUSAtotal2010309326295.0
2540NaNNaNUSAunder18201173902222.0
2541NaNNaNUSAtotal2011311582564.0
2542NaNNaNUSAunder18201273708179.0
2543NaNNaNUSAtotal2012313873685.0

2544 rows × 6 columns

# 重复的abbreviation列进行删除
abb_pop.drop(labels='abbreviation',axis=1,inplace=True)
# 查看存在缺失数据的列
abb_pop.isnull().any(axis=0)
state            True
state/region    False
ages            False
year            False
population       True
dtype: bool
# 汇总数据找到哪些state/region使得state的值为NaN,进行去重的操作
# 1、定位state列中的空值
ex = abb_pop['state'].isnull()
# 2、取出state中空值对应的行数据
abb_pop.loc[ex]
# 3、取出state空对应的简称数据
abb_pop.loc[ex]['state/region']
# 4、对第三步获取的简称进行去重
abb_pop.loc[ex]['state/region'].unique()
array(['PR', 'USA'], dtype=object)
# 为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的所有NaN
# 1、定位USA简称对应的全称
abb_pop['state/region'] == 'USA'
# 2、上述布尔值作为元数据的行索引,取出USA的行数据
abb_pop.loc[abb_pop['state/region'] == 'USA']
# 3、获取USA的行索引
indexs = abb_pop.loc[abb_pop['state/region'] == 'USA'].index
#4.将indexs这些行的state列的值批量填充成USA的全称
abb_pop.loc[indexs,'state'] = 'United State'
abb_pop['state/region'] == 'PR'
abb_pop.loc[abb_pop['state/region'] == 'PR']
indexs = abb_pop.loc[abb_pop['state/region'] == 'PR'].index
abb_pop.loc[indexs,'state'] = 'PPPRRR'
#检测state列中是否还存在空值
abb_pop['state'].isnull().sum()
# 汇总的数据和各州面积数据areas进行汇总
abb_pop_area = pd.merge(left=abb_pop,right=area,on='state',how='outer')
abb_pop_area.head()
statestate/regionagesyearpopulationarea (sq. mi)
0AlabamaALunder182012.01117489.052423.0
1AlabamaALtotal2012.04817528.052423.0
2AlabamaALunder182010.01130966.052423.0
3AlabamaALtotal2010.04785570.052423.0
4AlabamaALunder182011.01125763.052423.0
# 发现area(sq.mi)这一列有缺失数据,找出是哪些行,去除含有缺失数据的行
abb_pop_area['area (sq. mi)'].isnull()
# 将area (sq. mi)列中空对应的行数据取出
abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()]
# 获取了area (sq. mi)列中空对应的行索引
indexs = abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()].index
Int64Index([2448, 2449, 2450, 2451, 2452, 2453, 2454, 2455, 2456, 2457, 2458,
            2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469,
            2470, 2471, 2472, 2473, 2474, 2475, 2476, 2477, 2478, 2479, 2480,
            2481, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491,
            2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502,
            2503, 2504, 2505, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513,
            2514, 2515, 2516, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524,
            2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2534, 2535,
            2536, 2537, 2538, 2539, 2540, 2541, 2542, 2543],
           dtype='int64')
# 去除含有缺失数据的行
abb_pop_area.drop(labels=indexs,axis=0,inplace=True)
# 找出2010年的全民人口数据
abb_pop_area.query('year == 2010 & ages == "total"')
statestate/regionagesyearpopulationarea (sq. mi)
3AlabamaALtotal2010.04785570.052423.0
91AlaskaAKtotal2010.0713868.0656425.0
101ArizonaAZtotal2010.06408790.0114006.0
189ArkansasARtotal2010.02922280.053182.0
197CaliforniaCAtotal2010.037333601.0163707.0
283ColoradoCOtotal2010.05048196.0104100.0
293ConnecticutCTtotal2010.03579210.05544.0
379DelawareDEtotal2010.0899711.01954.0
389District of ColumbiaDCtotal2010.0605125.068.0
475FloridaFLtotal2010.018846054.065758.0
485GeorgiaGAtotal2010.09713248.059441.0
570HawaiiHItotal2010.01363731.010932.0
581IdahoIDtotal2010.01570718.083574.0
666IllinoisILtotal2010.012839695.057918.0
677IndianaINtotal2010.06489965.036420.0
762IowaIAtotal2010.03050314.056276.0
773KansasKStotal2010.02858910.082282.0
858KentuckyKYtotal2010.04347698.040411.0
869LouisianaLAtotal2010.04545392.051843.0
954MaineMEtotal2010.01327366.035387.0
965MontanaMTtotal2010.0990527.0147046.0
1050NebraskaNEtotal2010.01829838.077358.0
1061NevadaNVtotal2010.02703230.0110567.0
1146New HampshireNHtotal2010.01316614.09351.0
1157New JerseyNJtotal2010.08802707.08722.0
1242New MexicoNMtotal2010.02064982.0121593.0
1253New YorkNYtotal2010.019398228.054475.0
1338North CarolinaNCtotal2010.09559533.053821.0
1349North DakotaNDtotal2010.0674344.070704.0
1434OhioOHtotal2010.011545435.044828.0
1445OklahomaOKtotal2010.03759263.069903.0
1530OregonORtotal2010.03837208.098386.0
1541MarylandMDtotal2010.05787193.012407.0
1626MassachusettsMAtotal2010.06563263.010555.0
1637MichiganMItotal2010.09876149.096810.0
1722MinnesotaMNtotal2010.05310337.086943.0
1733MississippiMStotal2010.02970047.048434.0
1818MissouriMOtotal2010.05996063.069709.0
1829PennsylvaniaPAtotal2010.012710472.046058.0
1914Rhode IslandRItotal2010.01052669.01545.0
1925South CarolinaSCtotal2010.04636361.032007.0
2010South DakotaSDtotal2010.0816211.077121.0
2021TennesseeTNtotal2010.06356683.042146.0
2106TexasTXtotal2010.025245178.0268601.0
2117UtahUTtotal2010.02774424.084904.0
2202VermontVTtotal2010.0625793.09615.0
2213VirginiaVAtotal2010.08024417.042769.0
2298WashingtonWAtotal2010.06742256.071303.0
2309West VirginiaWVtotal2010.01854146.024231.0
2394WisconsinWItotal2010.05689060.065503.0
2405WyomingWYtotal2010.0564222.097818.0
# 计算各州的人口密度
midu = abb_pop_area['population'] / abb_pop_area['area (sq. mi)']
abb_pop_area['midu'] = midu
abb_pop_area.head()
statestate/regionagesyearpopulationarea (sq. mi)midu
0AlabamaALunder182012.01117489.052423.021.316769
1AlabamaALtotal2012.04817528.052423.091.897221
2AlabamaALunder182010.01130966.052423.021.573851
3AlabamaALtotal2010.04785570.052423.091.287603
4AlabamaALunder182011.01125763.052423.021.474601

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

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}

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'           
 }
需求
  • 加载数据
  • 查看数据的基本信息
  • 指定数据截取,将如下字段的数据进行提取,其他数据舍弃
    • 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主要支持谁
df = pd.read_csv('./data/usa_election.txt',low_memory=False)
df = df[['cand_nm','contbr_nm','contbr_st','contbr_employer','contbr_occupation','contb_receipt_amt','contb_receipt_dt']]
df.head()
cand_nmcontbr_nmcontbr_stcontbr_employercontbr_occupationcontb_receipt_amtcontb_receipt_dt
0Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED250.020-JUN-11
1Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED50.023-JUN-11
2Bachmann, MichelleSMITH, LANIERALINFORMATION REQUESTEDINFORMATION REQUESTED250.005-JUL-11
3Bachmann, MichelleBLEVINS, DARONDAARNONERETIRED250.001-AUG-11
4Bachmann, MichelleWARDENBURG, HAROLDARNONERETIRED300.020-JUN-11
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 536041 entries, 0 to 536040
Data columns (total 7 columns):
 #   Column             Non-Null Count   Dtype  
---  ------             --------------   -----  
 0   cand_nm            536041 non-null  object 
 1   contbr_nm          536041 non-null  object 
 2   contbr_st          536040 non-null  object 
 3   contbr_employer    525088 non-null  object 
 4   contbr_occupation  530520 non-null  object 
 5   contb_receipt_amt  536041 non-null  float64
 6   contb_receipt_dt   536041 non-null  object 
dtypes: float64(1), object(6)
memory usage: 28.6+ MB
#将所有的缺失数据填充成NOT PROVIDE
df.fillna(value='NOT PROVIDE',inplace=True)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 536041 entries, 0 to 536040
Data columns (total 7 columns):
 #   Column             Non-Null Count   Dtype  
---  ------             --------------   -----  
 0   cand_nm            536041 non-null  object 
 1   contbr_nm          536041 non-null  object 
 2   contbr_st          536041 non-null  object 
 3   contbr_employer    536041 non-null  object 
 4   contbr_occupation  536041 non-null  object 
 5   contb_receipt_amt  536041 non-null  float64
 6   contb_receipt_dt   536041 non-null  object 
dtypes: float64(1), object(6)
memory usage: 28.6+ MB
#异常值处理。将捐款金额<=0的数据删除
(df['contb_receipt_amt'] <= 0).sum()
5727
~(df['contb_receipt_amt'] <= 0)
df = df.loc[~(df['contb_receipt_amt'] <= 0)]
#新建一列为各个候选人所在党派party
df['party'] = df['cand_nm'].map(parties)
df.head()
cand_nmcontbr_nmcontbr_stcontbr_employercontbr_occupationcontb_receipt_amtcontb_receipt_dtparty
0Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED250.020-JUN-11Republican
1Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED50.023-JUN-11Republican
2Bachmann, MichelleSMITH, LANIERALINFORMATION REQUESTEDINFORMATION REQUESTED250.005-JUL-11Republican
3Bachmann, MichelleBLEVINS, DARONDAARNONERETIRED250.001-AUG-11Republican
4Bachmann, MichelleWARDENBURG, HAROLDARNONERETIRED300.020-JUN-11Republican
#查看party这一列中有哪些不同的元素
df['party'].unique()
array(['Republican', 'Democrat', 'Reform', 'Libertarian'], dtype=object)
df
cand_nmcontbr_nmcontbr_stcontbr_employercontbr_occupationcontb_receipt_amtcontb_receipt_dtparty
0Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED250.020-JUN-11Republican
1Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED50.023-JUN-11Republican
2Bachmann, MichelleSMITH, LANIERALINFORMATION REQUESTEDINFORMATION REQUESTED250.005-JUL-11Republican
3Bachmann, MichelleBLEVINS, DARONDAARNONERETIRED250.001-AUG-11Republican
4Bachmann, MichelleWARDENBURG, HAROLDARNONERETIRED300.020-JUN-11Republican
...........................
536036Perry, RickANDERSON, MARILEE MRS.XXINFORMATION REQUESTED PER BEST EFFORTSINFORMATION REQUESTED PER BEST EFFORTS2500.031-AUG-11Republican
536037Perry, RickTOLBERT, DARYL MR.XXT.A.C.C.LONGWALL MAINTENANCE FOREMAN500.030-SEP-11Republican
536038Perry, RickGRANE, BRYAN F. MR.XXINFORMATION REQUESTED PER BEST EFFORTSINFORMATION REQUESTED PER BEST EFFORTS500.029-SEP-11Republican
536039Perry, RickDUFFY, DAVID A. MR.XXDUFFY EQUIPMENT COMPANY INC.BUSINESS OWNER2500.030-SEP-11Republican
536040Perry, RickGORMAN, CHRIS D. MR.XXINFORMATION REQUESTED PER BEST EFFORTSINFORMATION REQUESTED PER BEST EFFORTS5000.029-SEP-11Republican

530314 rows × 8 columns

#统计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()
contb_receipt_dt  party      
01-APR-11         Reform             50.00
                  Republican      12635.00
01-AUG-11         Democrat       182198.00
                  Libertarian      1000.00
                  Reform           1847.00
                                   ...    
31-MAY-11         Republican     313839.80
31-OCT-11         Democrat       216971.87
                  Libertarian      4250.00
                  Reform           3205.00
                  Republican     751542.36
Name: contb_receipt_amt, Length: 1183, dtype: float64
#将表中日期格式转换为'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'] = df['contb_receipt_dt'].map(transform_date)
df.head()
cand_nmcontbr_nmcontbr_stcontbr_employercontbr_occupationcontb_receipt_amtcontb_receipt_dtparty
0Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED250.02011-6-20Republican
1Bachmann, MichelleHARVEY, WILLIAMALRETIREDRETIRED50.02011-6-23Republican
2Bachmann, MichelleSMITH, LANIERALINFORMATION REQUESTEDINFORMATION REQUESTED250.02011-7-05Republican
3Bachmann, MichelleBLEVINS, DARONDAARNONERETIRED250.02011-8-01Republican
4Bachmann, MichelleWARDENBURG, HAROLDARNONERETIRED300.02011-6-20Republican
# 查看老兵(DISABLED VETERAN)最支持的人是谁
# 取出仅含老兵职业的数据
df['contbr_occupation'] == 'DISABLED VETERAN'
old_bing_df = df.loc[df['contbr_occupation'] == 'DISABLED VETERAN']
old_bing_df.head()
cand_nmcontbr_nmcontbr_stcontbr_employercontbr_occupationcontb_receipt_amtcontb_receipt_dtparty
149790Obama, BarackMAHURIN, DAVIDFLVETERANS ADMINISTRATIONDISABLED VETERAN10.02012-1-17Democrat
150910Obama, BarackMAHURIN, DAVIDFLVETERANS ADMINISTRATIONDISABLED VETERAN20.02012-1-01Democrat
174041Obama, BarackKRUCHTEN, MICHAELILDISABLEDDISABLED VETERAN50.02011-12-02Democrat
175244Obama, BarackKRUCHTEN, MICHAELILDISABLEDDISABLED VETERAN250.02011-10-12Democrat
183790Obama, BarackBRYANT, J.L.KSRET ARMYDISABLED VETERAN100.02011-10-12Democrat
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

友培

数据皆开源!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值