- 需求:
- 导入文件,查看原始数据
- 将人口数据和各州简称数据进行合并
- 将合并的数据中重复的abbreviation列进行删除
- 查看存在缺失数据的列
- 找到有哪些state/region使得state的值为NaN,进行去重操作
- 为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的所有NaN
- 合并各州面积数据areas
- 我们会发现area(sq.mi)这一列有缺失数据,找出是哪些行
- 去除含有缺失数据的行
- 找出2010年的全民人口数据
- 计算各州的人口密度
- 排序,并找出人口密度最高的州
import numpy as np
import pandas as pd
from pandas import DataFrame
abb = pd.read_csv('./data/state-abbrevs.csv')
area = pd.read_csv('./data/state-areas.csv')
pop = pd.read_csv('./data/state-population.csv')
abb_pop = pd.merge(abb,pop,left_on='abbreviation',right_on='state/region',how='outer')
abb_pop.head()
abb_pop.drop(labels='abbreviation',axis=1,inplace=True)
abb_pop.head()
abb_pop.isnull().any(axis=0)
abb_pop.info()
abb_pop.head()
abb_pop['state'].isnull()
abb_pop.loc[abb_pop['state'].isnull()]
abb_pop.loc[abb_pop['state'].isnull()]['state/region']
abb_pop.loc[abb_pop['state'].isnull()]['state/region'].unique()
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.iloc[indexs]
abb_pop.loc[indexs,'state'] = 'United States'
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'
abb_pop_area = pd.merge(abb_pop,area,how='outer')
abb_pop_area['area (sq. mi)'].isnull()
abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()]
indexs = abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()].index
abb_pop_area.drop(labels=indexs,axis=0,inplace=True)
abb_pop_area.query('ages == "total" & year == 2010')
abb_pop_area['midu'] = abb_pop_area['population'] / abb_pop_area['area (sq. mi)']
abb_pop_area
abb_pop_area.sort_values(by='midu',axis=0,ascending=False).iloc[0]['state']