PySpark 学习笔记三

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()))
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值