美国人口普查数据分析

# 美国人口普查数据分析

需求:
  导入文件,查看原始数据
  将人口数据和各州简称数据进行合并
  将合并的数据中重复的abbreviation列进行删除
  查看存在缺失数据的列
  找到有哪些state/region使得state的值为NaN,进行去重操作
  为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的所有NaN
  合并各州面积数据areas
  我们会发现area(sq.mi)这一列有缺失数据,找出是哪些行
  去除含有缺失数据的行
  找出2010年的全民人口数据
  计算各州的人口密度
  排序,并找出人口密度最高的五个州 df.sort_values()

 

import numpy as np
from pandas import DataFrame,Series
import pandas as pd

abb = pd.read_csv('./data/state-abbrevs.csv')    #州简称
pop = pd.read_csv('./data/state-population.csv') #州人口普查 未成年/全民人口 普查时间
area = pd.read_csv('./data/state-areas.csv')     #州面积

#将人口数据和各州简称数据进行合并
abb_pop = pd.merge(abb,pop,how='outer',left_on='abbreviation',right_on='state/region')
abb_pop.head(1)

#将合并的数据中重复的abbreviation列进行删除
abb_pop.drop(labels='abbreviation',axis=1,inplace=True) #列

# 查看存在缺失数据的列
abb_pop.isnull().any(axis=0) #

#找到有哪些state/region使得state的值为NaN,进行去重操作
indexs = abb_pop['state'][abb_pop['state'].isnull()].index
abb_pop.iloc[indexs]['state/region'].unique()

# 为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的所有NaN
indexs = abb_pop.loc[abb_pop['state/region'] == 'PR'].index
abb_pop.loc[indexs,'state'] = 'PPPRRR'
#找到有哪些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()
法二
# 先将USA简称对应的全称定位到
abb_pop['state/region']=='USA'
abb_pop.loc[abb_pop['state/region']=='USA']
indexs = abb_pop.loc[abb_pop['state/region']=='USA'].index
abb_pop.loc[indexs,'state'] = 'United State'

# 合并各州面积数据areas
abb_pop_area = pd.merge(abb_pop,area,'outer')  #可以查看head()

# 去除含有缺失数据的行
abb_pop_area['area (sq. mi)'].isnull()
abb_pop_area = abb_pop_area.loc[~(abb_pop_area['area (sq. mi)'].isnull())]

#找出2010年的全民人口数据
abb_pop_area.query('ages == "total"&year=="2010"')

# 计算各州的人口密度
midu = abb_pop_area['population']/abb_pop_area['area (sq. mi)']
abb_pop_area['midu'] = midu
abb_pop_area.head()

#对密度进行排序    列   acs升序
abb_pop_area.sort_values(by='midu',axis=0,ascending=False).head(5)

 

posted @ 2019-05-14 20:42  追风zz  阅读(1412)  评论(1编辑  收藏  举报