缺失数据的处理
1.pandas中对none的处理
自动把none 当作缺失数据
import pandas as pd
df= pd.Series([16,16,22,23,None])
df
0 16.0
1 16.0
2 22.0
3 23.0
4 NaN
dtype: float64
在nupmy中None 可以与数字相加
import numpy as np
np.nan+2
nan
查看数据中哪部分缺失
import numpy as np
import pandas as pd
s=pd.Series([16,2,1,5,None])
s
0 16.0
1 2.0
2 1.0
3 5.0
4 NaN
dtype: float64
使用isna检测
s.isna()
0 False
1 False
2 False
3 False
4 True
dtype: bool
datafram中也一样
b=pd.DataFrame({'name':['liu','chen','dong'],'sex':['m','f',np.nan]})
b
name sex
0 liu m
1 chen f
2 dong NaN
b.isna()
name sex
0 False False
1 False False
2 False True
如果数据集很大,这种方式就会很麻烦!!!
用any()检测列下面的缺失情况
b.isna().any()
name False
sex True
dtype: bool
计算缺失率
(b.shape[0]-b.count())/b.shape[0]
name 0.000000
sex 0.333333
dtype: float64
(b.shape[1]-b.T.count())/b.shape[1]#shape[0]表示行数,shape[1]表示列数
0 0.0
1 0.0
2 0.5
dtype: float64
删除缺失值的那一行
b.dropna()
name sex
0 liu m
1 chen f
选择性删除其内容全是缺失值的行或列
b.dropna(axis=0,how='all')# axis=0是行,how 是全部是缺失值的时候才删除该行或列
name sex
0 liu m
1 chen f
2 dong NaN
设置缺失值阈值
b.dropna(thresh=2)# 非缺失值的数量小于2则删除该行
name sex
0 liu m
1 chen f
缺失值填充
b.fillna('m')
name sex
0 liu m
1 chen f
2 dong m
填充上一个数字
b.fillna(method='ffill') # bfill填充缺失值后面的那个值
name sex
0 liu m
1 chen f
2 dong f