3 Prepare Data for Modeling
所有的数据都是脏的,不管是从网上下载的数据集,或其他来源。直到你测试和证明你的数据处于干净状态才能用来建模。因此,为了建模需要清理数据集,还需要检查数据集的特征分布,并确认它们符合预定义的标准。
3.1 检查重复项、缺失值和异常值
- 重复项
生成一个简单的dataframe如下:
>>> df = spark.createDataFrame([
... (1,144.5,5.9,33,'M'),
... (2,167.2,5.4,45,'M'),
... (3,124.1,5.2,23,'F'),
... (4,144.5,5.9,33,'M'),
... (5,133.2,5.7,54,'F'),
... (3,124.1,5.2,23,'F'),
... (5,129.2,5.3,42,'M'),
... ],['id','weight','height','age','gender'])
显然,这个数据只有几行,一眼就可以发现是否有重复值。但对于百万级别的数据呢?
第一件事,就是用.distinct()方法检查。
>>> print('count of rows: {
0}'.format(df.count()))
count of rows: 7
>>> print('count of distinct rows: {
0}'.format(df.distinct().count()))
count of distinct rows: 6
然后,用 .dropDuplicates(…)去掉重复项。
>>> df = df.dropDuplicates()
>>> df.show()
+---+------+------+---+------+
| id|weight|height|age|gender|
+---+------+------+---+------+
| 5| 133.2| 5.7| 54| F|
| 5| 129.2| 5.3| 42| M|
| 1| 144.5| 5.9| 33| M|
| 4| 144.5| 5.9| 33| M|
| 2| 167.2| 5.4| 45| M|
| 3| 124.1| 5.2| 23| F|
+---+------+------+---+------+
上面的代码根据ID列去除了完全重复的一行,我们可以使用ID列以外的列再次去重。
>>> print ('count of ids: {
0}'.format(df.count()))
count of ids: 6
>>> print('count of distinct ids: {
0}'.format(df.select([c for c in df.columns if c!='id']).distinct().count()))