需求:
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)
原文:https://www.cnblogs.com/linranran/p/13307951.html