pandas 案例分析:美国人口案例分析
'''
需求:
导入文件,查看原始数据
将人口数据和各州简称数据进行合并
将合并的数据中重复的abbreviation列进行删除
查看存在缺失数据的列
找到有哪些state/region使得state的值为NaN,进行去重操作
为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的所有NaN
合并各州面积数据areas
我们会发现area(sq.mi)这一列有缺失数据,找出是哪些行
去除含有缺失数据的行
找出2010年的全民人口数据
计算各州的人口密度
排序,并找出人口密度最高的五个州 df.sort_values()
'''
import numpy as np
import pandas as pd
s_abbrevs = pd.read_csv('../datasets/state-abbrevs.csv')
print(s_abbrevs.head())
s_population = pd.read_csv('../datasets/state-population.csv')
print(s_population.head())
s_areas = pd.read_csv('../datasets/state-areas.csv')
print(s_areas.head())
abb_pop = pd.merge(s_abbrevs, s_population, left_on='abbreviation', right_on='state/region', how='outer')
print(abb_pop.head())
abb_pop = abb_pop.drop(columns='abbreviation')
'''
state True
abbreviation True
state/region False
ages False
year False
population True
'''
print(abb_pop.isnull().any(axis=0))
print(abb_pop[abb_pop['state'].isnull()]['state/region'].unique())
index_PR = abb_pop[abb_pop['state/region'] == 'PR'].index
print(index_PR)
abb_pop.loc[index_PR, 'state'] = 'PUERTO'
index_USA = abb_pop[abb_pop['state/region'] == 'USA'].index
print(index_USA)
abb_pop.loc[index_USA, 'state'] = 'America'
print(abb_pop[abb_pop['state/region'] == 'PR'].head())
print(abb_pop[abb_pop['state/region'] == 'USA'].head())
print(abb_pop.isnull().any(axis=0))
areas_abb_pop = pd.merge(s_areas, abb_pop, left_on='state', right_on='state', how='outer')
print(areas_abb_pop.head())
areas_abb_pop.set_index('state', inplace=True)
print(areas_abb_pop.isnull().any(axis=0))
areas_abb_pop.dropna(inplace=True)
query_2010 = areas_abb_pop.query('ages == "total" & year == 2010')
print(query_2010.head())
midu = query_2010['population'] / query_2010['area (sq. mi)']
print(midu)
midu = midu.sort_values(ascending=True)
print(midu.sort_values().tail())
print(midu.sort_values().head())