本人以简书作者 SeanCheney 系列专题文章并结合原书为学习资源,记录个人笔记,仅作为知识记录及后期复习所用,原作者地址查看 简书 SeanCheney,如有错误,还望批评指教。——ZJ
原作者:SeanCheney | 《利用 Python 进行数据分析·第2版》第7章 数据清洗和准备 | 來源:简书
环境: Python 3.6
Chapter 7 Data Cleaning and Preparation
- 在数据分析和建模的过程中,相当多的时间要用在数据准备上:加载、清理、转换以及重塑。这些工作会占到分析师时间的 80% 或更多。有时,存储在文件和数据库中的数据的格式不适合某个特定的任务。
- pandas 和内置的 Python 标准库提供了一组高级的、灵活的、快速的工具,可以让你轻松地将数据规变为想要的格式。
- 在本章中,我会讨论处理缺失数据、重复数据、字符串操作和其它分析数据转换的工具。下一章,我会关注于用多种方法合并、重塑数据集。
7.1 处理缺失数据
在许多数据分析工作中,缺失数据是经常发生的。 pandas 的目标之一就是尽量轻松地处理缺失数据。例如, pandas 对象的所有描述性统计默认都不包括缺失数据。
缺失数据在 pandas 中呈现的方式有些不完美,但对于大多数用户可以保证功能正常。对于数值数据, pandas 使用浮点值 NaN(Not a Number)表示缺失数据。我们称其为哨兵值,可以方便的检测出来:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: string_data = pd.Series(['aardvark', 'artichoke', np.nan, 'avocado'])
In [4]: string_data
Out[4]:
0 aardvark
1 artichoke
2 NaN
3 avocado
dtype: object
In [5]: string_data.isnull()
Out[5]:
0 False
1 False
2 True
3 False
dtype: bool
- 在 pandas 中,我们采用了 R 语言中的惯用法,即将缺失值表示为 NA ,它表示不可用 not available。
- 在统计应用中, NA 数据可能是不存在的数据或者虽然存在,但是没有观察到(例如,数据采集中发生了问题)。
- 当进行数据清洗以进行分析时,最好直接对缺失数据进行分析,以判断数据采集的问题或缺失数据可能导致的偏差。
Python 内置的 None 值在对象数组中也可以作为 NA:
In [6]: type(string_data)
Out[6]: pandas.core.series.Series
In [7]: string_data[0] = None
In [8]: string_data.isnull()
Out[8]:
0 True
1 False
2 True
3 False
dtype: bool
pandas 项目中还在不断优化内部细节以更好处理缺失数据,像用户API功能,例如 pandas .isnull,去除了许多恼人的细节。表7-1列出了一些关于缺失数据处理的函数。
滤除缺失数据
- 过滤掉缺失数据的办法有很多种。你可以通过
pandas.isnull
或布尔索引的手工方法,但 dropna 可能会更实用一些。 - 对于一个 Series , dropna 返回一个仅含非空数据和索引值的 Series :
In [9]: from numpy import nan as NA
In [10]: data = pd.Series([1, NA, 3.5, NA, 7])
In [11]: data.dropna()
Out[11]:
0 1.0
2 3.5
4 7.0
dtype: float64
In [12]: data
Out[12]:
0 1.0
1 NaN
2 3.5
3 NaN
4 7.0
dtype: float64
这等价于:
In [14]: data[data.notnull()]
Out[14]:
0 1.0
2 3.5
4 7.0
dtype: float64
- 而对于 DataFrame 对象,事情就有点复杂了。你可能希望丢弃全 NA 或含有 NA 的行或列。
- dropna 默认丢弃任何含有缺失值的行:
In [15]: data = pd.DataFrame([[1., 6.5, 3.], [1., NA, NA],
...: [NA, NA, NA], [NA, 6.5, 3.]], index=['one', 't
...: wo', 'three', 'four'], columns=['first', 'second', 'third'])
...:
...:
In [16]: data
Out[16]:
first second third
one 1.0 6.5 3.0
two 1.0 NaN NaN
three NaN NaN NaN
four NaN 6.5 3.0
In [17]: cleaned = data.dropna()
In [18]: cleaned
Out[18]:
first second third
one 1.0 6.5 3.0
传入how='all'
将只丢弃全为 NA 的那些行
In [19]: data.dropna(how='all')
Out[19]:
first second third
one 1.0 6.5 3.0
two 1.0 NaN NaN
four NaN 6.5 3.0
用这种方式丢弃列(全是 NA 的列),只需传入axis=1
即可:
In [20]: data['forth'] = NA
In [21]: data
Out[21]:
first second third forth
one 1.0 6.5 3.0 NaN
two 1.0 NaN NaN NaN
three NaN NaN NaN NaN
four NaN 6.5 3.0 NaN
In [22]: data.dropna(axis=1, how='all')
Out[22]:
first second third
one 1.0 6.5 3.0
two 1.0 NaN NaN
three NaN NaN NaN
four NaN 6.5 3.0
另一个滤除 DataFrame 行的问题涉及时间序列数据。假设你只想留下一部分观测数据,可以用 thresh 参数实现此目的:
In [23]: df = pd.DataFrame(np.random.randn(7,3))
In [24]: df.iloc[:4, 1] = NA
In [25]: df
Out[25]:
0 1 2
0 -0.052880 NaN 0.192669
1 0.440543 NaN -0.058121
2 0.297282 NaN -0.808425
3 -0.429874 NaN -0.965913
4 0.132290 0.251065 0.853049
5 1.190240 -1.118041 -0.075022
6 0.530970 0.033641 -0.473945
In [26]: df.iloc[:2, 2] = NA
In [27]: df
Out[27]:
0 1 2
0 -0.052880 NaN NaN
1 0.440543 NaN NaN
2 0.297282 NaN -0.808425
3 -0.429874 NaN -0.965913
4 0.132290 0.251065 0.853049
5 1.190240 -1.118041 -0.075022
6 0.530970 0.033641 -0.473945
In [28]: df.dropna()
Out[28]:
0 1 2
4 0.13229 0.251065 0.853049
5 1.19024 -1.118041 -0.075022
6 0.53097 0.033641 -0.473945
In [29]: df.dropna(thresh=2) # 索引 0 1 行 含有 NA 的去掉了
Out[29]:
0 1 2
2 0.297282 NaN -0.808425
3 -0.429874 NaN -0.965913
4 0.132290 0.251065 0.853049
5 1.190240 -1.118041 -0.075022
6 0.530970 0.033641 -0.473945
填充缺失数据
- 你可能不想滤除缺失数据(有可能会丢弃跟它有关的其他数据),而是希望通过其他方式填补那些“空洞”。
- 对于大多数情况而言, fillna 方法是最主要的函数。通过一个常数调用 fillna 就会将缺失值替换为那个常数值:
In [30]: df.fillna(0)
Out[30]:
0 1 2
0 -0.052880 0.000000 0.000000
1 0.440543 0.000000 0.000000
2 0.297282 0.000000 -0.808425
3 -0.429874 0.000000 -0.965913
4 0.132290 0.251065 0.853049
5 1.190240 -1.118041 -0.075022
6 0.530970 0.033641 -0.473945
若是通过一个字典调用 fillna ,就可以实现对不同的列填充不同的值:
In [31]: df.fillna({
1: 0.5, 2: 0})
Out[31]:
0 1 2
0 -0.052880 0.500000 0.000000
1 0.440543 0.500000 0.000000
2 0.297282 0.500000 -0.808425
3 -0.429874 0.500000 -0.965913
4 0.132290 0.251065 0.853049
5 1.190240 -1.118041 -0.075022
6 0.530970 0.033641 -0.473945
fillna 默认会返回新对象,但也可以对现有对象进行就地修改:
In [32]: _ = df.fillna(0, inplace= True)
In [33]: df
Out[33]:
0 1 2
0 -0.052880 0.000000 0.000000
1 0.440543 0.000000 0.000000
2 0.297282 0.000000 -0.808425
3 -0.429874 0.000000 -0.965913
4 0.132290 0.251065 0.853049
5 1.190240 -1.118041 -0.075022
6 0.530970 0.033641 -0.473945
对 reindexing 有效的那些插值方法也可用于 fillna :
In [34]: df = pd.DataFrame(np.random.randn(6,3))
In [35]: df.iloc[2:, 1] = NA
In [36]: df
Out[36]:
0 1 2
0 -0.775110 0.000504 1.445061
1 -0.469458 0.727227 -0.166666
2 0.019312 NaN -0.915137
3 -1.477259 NaN 0.423064
4 1.620944 NaN 1.165360
5 0.388970 NaN 0.230785
In [37]: df.iloc[4:, 2] = NA
In [38]: df
Out[38]:
0 1 2
0 -0.775110 0.000504 1.445061
1 -0.469458 0.727227 -0.166666
2 0.019312 NaN -0.915137
3 -1.477259 NaN 0.423064
4 1.620944 NaN NaN
5 0.388970 NaN NaN
In [39]: df.fillna(method='ffill')
Out[39]:
0 1 2
0 -0.775110 0.000504 1.445061
1 -0.469458 0.727227 -0.166666
2 0.019312 0.727227 -0.915137
3 -1.477259 0.727227 0.423064
4 1.620944 0.727227 0.423064
5 0.388970 0.727227 0.423064
In [40]: df.fillna(method='ffill', limit=2)
Out[40]:
0 1 2
0 -0.775110 0.000504 1.44