PySpark使用分组平均值填充缺失/错误的值 [英] PySpark fill missing/wrong value with grouped mean

查看:13
本文介绍了PySpark使用分组平均值填充缺失/错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spark数据帧,其中一个值丢失,一个值错误。

from pyspark.sql import Row
from pyspark.sql.types import StringType, DoubleType, StructType, StructField
# fruit sales data
data = [Row(id='01', fruit='Apple', qty=5.0),
        Row(id='02', fruit='Apple', qty=1.0),
        Row(id='03', fruit='Apple', qty=None),
        Row(id='04', fruit='Pear', qty=6.0),
        Row(id='05', fruit='Pear', qty=2.0),
        Row(id='06', fruit='Mango', qty=6.0),
        Row(id='07', fruit='Mango', qty=-4.0),
        Row(id='08', fruit='Mango', qty=2.0)]
# create dataframe
df = spark.createDataFrame(data)
df.show()
+-----+---+----+
|fruit| id| qty|
+-----+---+----+
|Apple| 01| 5.0|
|Apple| 02| 1.0|
|Apple| 03|null|
| Pear| 04| 6.0|
| Pear| 05| 2.0|
|Mango| 06| 6.0|
|Mango| 07|-4.0|
|Mango| 08| 2.0|
+-----+---+----+

按整列平均值进行填充非常简单。但我怎么做才能做到分组平均呢?为了说明,我希望将第3行中的null替换为mean(qty)-在本例中为(5+1)/2=3。类似地,第7行中的-4.0是错误的值(非负数),我希望将其替换为(6+2)/2=4

在纯Python中,我会这样做:

def replace_with_grouped_mean(df, value, column, to_groupby):
    invalid_mask = (df[column] == value)
    # get the mean without the invalid value
    means_by_group = (df[~invalid_mask].groupby(to_groupby)[column].mean())
    # get an array of the means for all of the data
    means_array = means_by_group[df[to_groupby].values].values
    # assign the invalid values to means
    df.loc[invalid_mask, column] = means_array[invalid_mask]
    return df

并最终做到:

x = replace_with_grouped_mean(df=df, value=-4, column='qty', to_groupby='fruit')

然而,我不太确定如何在PySpark中实现这一点。感谢您的帮助/指点!

推荐答案

注意事项:当我们执行GROUP BY时,Null的行将被忽略。如果我们有3行,其中一行的值Null,则Average With被2整除,而不是3,因为第三个值是Null。这里的关键是使用Window()函数。

from pyspark.sql.functions import avg, col, when
from pyspark.sql.window import Window
w = Window().partitionBy('fruit')

#Replace negative values of 'qty' with Null, as we don't want to consider them while averaging.
df = df.withColumn('qty',when(col('qty')<0,None).otherwise(col('qty')))
df = df.withColumn('qty',when(col('qty').isNull(),avg(col('qty')).over(w)).otherwise(col('qty')))
df.show()
+-----+---+---+
|fruit| id|qty|
+-----+---+---+
| Pear| 04|6.0|
| Pear| 05|2.0|
|Mango| 06|6.0|
|Mango| 07|4.0|
|Mango| 08|2.0|
|Apple| 01|5.0|
|Apple| 02|1.0|
|Apple| 03|3.0|
+-----+---+---+

这篇关于PySpark使用分组平均值填充缺失/错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆