需求:dom
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')excel
将人口数据和各州简称数据进行合并
abb_pop = pd.merge(abb,pop,left_on='abbreviation',right_on='state/region',how='outer')
abb_pop.head(3)code
将合并的数据中重复的abbreviation列进行删除
abb_pop.drop(labels='abbreviation',axis=1,inplace=True)排序
查看存在缺失数据的列
abb_pop.isnull().any(axis=0) # notnull()和all() 里面还得填axis啊索引
找到有哪些state/region使得state的值为NaN,进行去重操做
abb_pop.head(5)数据分析
abb_pop['state'].isnull()数学
abb_pop.loc[abb_pop['state'].isnull()]pandas
abb_pop.loc[abb_pop['state'].isnull()]['state/region'].unique()it
结果--->array(['USA','PR'], dtype=object)
为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的全部NaN
给state的NAN补United States
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 States'
同理处理'PR'
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'
<u># 提醒不要忘了loc取行,不能直接取(df)
合并各州面积数据areas
abb_pop_area = pd.merge(abb_pop,area,how='outer')
<u># 提醒不要忘了how
咱们会发现area(sq.mi)这一列有缺失数据,找出是哪些行
去除含有缺失数据的行
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()].indexabb_pop_area.drop(labels=indexs,axis=0,inplace=True)
找出2010年的全民人口数据
df_2010 = abb_pop_area.query('year == 2010 & ages == "total"')
query筛选
计算各州的人口密度
abb_pop_area['midu'] = abb_pop_area['population'] / abb_pop_area['area (sq. mi)']
abb_pop_area.head(1)
排序,并找出人口密度最高的五个州 df.sort_values()
abb_pop_area.sort_values(by='midu',ascending=False)['state'].unique()[0:5]
练习7:
简述None与NaN的区别
假设张三李四参加模拟考试,但张三由于忽然想明白人生放弃了英语考试,所以记为None,请据此建立一个DataFrame,命名为ddd3
老师决定根据用数学的分数填充张三的英语成绩,如何实现? 用李四的英语成绩填充张三的英语成绩?
============================================
import random
ddd = DataFrame(data =np.random.randint(90,130,size=(2,2)),index=['英语','数学'],columns=['张三','李四'])
ddd
ddd.loc['数学','张三'] = np.nan
ddd
ddd.fillna(method='ffill',axis=0)
ddd.fillna(method='bfill',axis=1)
练习20:
新增两列,分别为张3、李四的成绩状态,若是分数低于90,则为"failed",若是分数高于120,则为"excellent",其余则为"pass"
df chengji(s): if s<90: return 'failed' if s>120: return 'excellent' else: return 'pass' 【提示】使用函数做为map的参数
def kaoshi(s):
if s<6000:
return 'failed'
if s>7200:
return 'excellent'
else:
return 'pass'
df['after_sal'] = df['salary'].map(kaoshi)# 也是
df