-1

I want to replace NA with mean and median based on multiple columns with help of window function in pyspark

Sample Input:

enter image description here

Required Output for mean:

enter image description here

Required output for median: Output will be same as above but need to replace based on median and can't find function in pyspark.sql.functions in pyspark

1 Answers1

0

Creating sample dataframe:

from pyspark.sql.window import Window
from pyspark.sql import functions as F

list=([1,5,4],
    [1,5,None],
    [1,5,4],
    [1,5,4],
    [2,5,1],
    [2,5,2],
    [2,5,None],
    [2,5,None])
df=spark.createDataFrame(list,['I_id','p_id','xyz'])
df.show()

+----+----+----+
|I_id|p_id| xyz|
+----+----+----+
|   1|   5|   4|
|   1|   5|null|
|   1|   5|   4|
|   1|   5|   4|
|   2|   5|   1|
|   2|   5|   2|
|   2|   5|null|
|   2|   5|null|
+----+----+----+

Creating Window and filling nulls:

w=Window().partitionBy("I_id","p_id")
df.withColumn("mean",F.mean("xyz").over(w))\
.withColumn("xyz", F.when(F.col("xyz").isNull(),F.col("mean")).otherwise(F.col("xyz")))\
.drop("mean").show()

+----+----+---+
|I_id|p_id|xyz|
+----+----+---+
|   1|   5|4.0|
|   1|   5|4.0|
|   1|   5|4.0|
|   1|   5|4.0|
|   2|   5|1.0|
|   2|   5|2.0|
|   2|   5|1.5|
|   2|   5|1.5|
+----+----+---+
murtihash
  • 8,030
  • 1
  • 14
  • 26