数据分析 第二章
第一节 数据清洗及特征处理
我们所处理的数据一般是不干净的,即数据中有缺失值,有一些异常点,需要经过处理才能进行后面的分析和建模,所以我们在使用数据前要进行的处理过程成为数据清洗。
缺失值观察与处理
数据缺失经常发生,pandas的目标之一就是尽量轻松地处理数据。例如,pandas对象的所有描述性统计默认都不包括缺失数据。
对于数值数据,pandas使用浮点值NaN(Not a Number)表示缺失数据,我们称之为哨兵值,可以方便的检测出来:
例子:
In [10]:string_data = pd.Series(['aardvark', 'artichoke', np.nan, 'avocado'])
In [11]: string_data
Out[11]:
0 aardvark
1 artichoke
2 NaN
3 avocado
dtype: object
In [12]: string_data.isnull()
Out[12]:
0 False
1 False
2 True
3 False
dtype: bool
Python内置的none值在对象数组中也可以作为NA:
In [13]: string_data[0] = None
In [14]: string_data.isnull()
Out[14]:
0 True
1 False
2 True
3 False
dtype: bool
关于一些缺失数据处理的函数
方法 | 说明 |
---|---|
dropna | 根据各标签的值中是否存在缺失数据对轴标签进行过滤,可通过阈值调节对缺失值的容忍度 |
fillna | 用指定值或插值方法(如ffill或bfill)填充缺失数据 |
isnull | 返回一个含有布尔值的对象,这些布尔值表示哪些值 |
notnull | isnull的否定式 |
滤除缺失数据
使用dropna滤除缺失数据,对于一个Series,dropna返回一个仅含非空数据和索引值的Series:
In [15]: from numpy import nan as NA
In [16]: data = pd.Series([1, NA, 3.5, NA, 7])
In [17]: data.dropna()
Out[17]:
0 1.0
2 3.5
4 7.0
dtype: float64
#等价于
In [18]: data[data.notnull()]
Out[18]:
0 1.0
2 3.5
4 7.0
dtype: float64
对于DataFrame对象,dropna默认丢弃任何含有缺失值的行
例子:
In [19]:data = pd.DataFrame([[1., 6.5, 3.], [1., NA, NA], [NA, NA, NA], [NA, 6.5, 3.]])
In [20]:cleaned = data.dropna()
In [21]:data
Out[21]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3.0
In [22]: cleaned
Out[22]:
0 1 2
0 1.0 6.5 3.0
#传入how='all'将只丢弃全为NA的那些行
In [23]: data.dropna(how='all')
Out[23]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
3 NaN 6.5 3.0
#丢弃全为NA的列,只需传入axis = 1即可:
In [24]: data[4] = NA
In [25]: data
Out[25]:
0 1 2 4
0 1.0 6.5 3.0 NaN
1 1.0 NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN 6.5 3.0 NaN
In [26]: data.dropna(axis=1, how='all')
Out[26]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3.0