我有一个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)
,将Apple
-在这种情况下为(5 + 1)/ 2 = 3。类似地,我要替换为(6 + 2)/ 2 = 4
-4.0
是错误的值(无负qty)
在纯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中实现这一目标。任何帮助/指针都表示赞赏!
答案 0 :(得分:1)
要点::分组时,具有Null
的行将被忽略。如果我们有3行,其中一行的值为Null
,则将平均值除以2,而不是3,因为第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|
+-----+---+---+