dataframe 空值替换为0_DataFrame的去重,none值填充及异常值处理2018-05-23

本文介绍了如何使用Spark DataFrame进行数据去重、填充空值(None)以及处理异常值。首先展示如何通过dropDuplicates()方法去重,然后通过fillna()方法填充空值,并使用approxQuantile()计算四分位数来识别和处理异常值。
摘要由CSDN通过智能技术生成

spark 数据建模准备

去重

#初始化spark

from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local[*]").appName("shuangyu").getOrCreate()

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"])

#分别打印dataframe未去重和去重后的行数

print("count of rows: {}".format(df.count()))

print("count of distinct rows: {}".format(df.distinct().count()))

count of rows: 7

count of distinct rows: 6

#去掉重复的行

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后是否有重复的数据

print("counts of ids: {}".format(df.count()))

print("counts of distinct ids: {}".format(df.select([c for c in df.columns if c != "id"]).distinct().count()))

counts of ids: 6

counts of distinct ids: 5

#发现有2行出去ID外其它都是重复的,现在要去掉其中的一行

df = df.dropDuplicates(subset = [c for c in df.columns if c != "id"])

df.show()

+---+------+------+---+------+

| id|weight|height|age|gender|

+---+------+------+---+------+

| 5| 133.2| 5.7| 54| F|

| 1| 144.5| 5.9| 33| M|

| 2| 167.2| 5.4| 45| M|

| 3| 124.1| 5.2| 23| F|

| 5| 129.2| 5.3| 42| M|

+---+------+------+---+------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值