一、了解缺失值
- 通常使用 NA('not available')来代指缺失值
- 在Pandas的数据结构中,缺失值使用 NaN('Not a Number')进行标识
除了汇总统计方法,还可以使用isnull()来对数据中缺失的样本占比、特征大致的缺失情况进行了解。
>>> df =pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']), ... 'two':pd.Series([1,3,2,7],index=['a','b','c','d']), ... 'three':pd.Series([3,8,3],index=['d','a','c'])}) >>> df one two three a 1.0 1 8.0 b 2.0 3 NaN c 3.0 2 3.0 d NaN 7 3.0 #缺失值的数量分析 >>> df.isnull() one two three a False False False b False False True c False False False d True False False >>> df.isnull().sum() one 1 two 0 three 1 dtype: int64
二、缺失值填充
使用fillna()方法进行缺失值填补
填充方式分为以下几种:
(1)使用同一个值填补所有的缺失值
>>> df.fillna('用我填充') one two three a 1 1 8 b 2 3 用我填充 c 3 2 3 d 用我填充 7 3
(2)向前填充、向后填充--->通过设置参数method参数来实现
method参数 | 说明 |
ffill或pad | 向前填充值 |
bfill或backfill | 向后填充值 |
#向前填充 >>> df.fillna(method='pad') one two three a 1.0 1 8.0 b 2.0 3 8.0 c 3.0 2 3.0 d 3.0 7 3.0 #向后填充 >>> df.fillna(method='bfill') one two three a 1.0 1 8.0 b 2.0 3 3.0 c 3.0 2 3.0 d NaN 7 3.0
(3)对不同列的缺失值使用不同的值进行填补
可以使用列表的方式,如下:
>>> df.fillna({'one':1,'three':3}) one two three a 1.0 1 8.0 b 2.0 3 3.0 c 3.0 2 3.0 d 1.0 7 3.0