问题描述
所以我想做的是用每个商店组的平均收入填充我在数据框中具有的收入列的空值。
原始数据框:
df = spark.createDataFrame(
[
('Store 1',1,448),('Store 1',2,None),3,499),44,432),(None,None,('Store 2',355),345),387),4,312),555),10,None)
],['Store','WeekInMonth','Revenue']
)
我已经从原始数据中创建了第二个数据框,但在此,我只是想获取每个数据框的平均值
df2 = df.groupBy('Store').avg('Revenue')
df2 = df2.select("Store",col("avg(Revenue)").alias("Revenue")).where("Store = 'Store 2' or Store = 'Store 1'")
display(df2)
我想做的是用每个商店的df2的平均值填充第一个数据帧上的Null值。
解决方法
要将空值替换为每家商店的平均收入,请使用window
函数。
df.show()
+-------+-----------+-------+
| Store|WeekInMonth|Revenue|
+-------+-----------+-------+
|Store 1| 1| 448|
|Store 1| 2| null|
|Store 1| 3| 499|
|Store 1| 44| 432|
|Store 2| null| 345|
|Store 2| null| 555|
|Store 2| 1| 355|
|Store 2| 1| 355|
|Store 2| 3| 387|
|Store 2| 4| 312|
| null| null| null|
| null| 10| null|
+-------+-----------+-------+
计算每个窗口的平均值,并在revenue
处将mean
替换为null
。
from pyspark.sql.functions import *
from pyspark.sql.window import Window
from pyspark.sql import functions as F
w=Window().partitionBy("Store")
df.withColumn("mean",F.mean("Revenue").over(w))\
.withColumn("Revenue",F.when(col("Revenue").isNull(),col("mean"))\
.otherwise(col("Revenue"))).drop("mean").show()
+-------+-----------+-----------------+
| Store|WeekInMonth| Revenue|
+-------+-----------+-----------------+
|Store 1| 1| 448.0|
|Store 1| 2|459.6666666666667|
|Store 1| 3| 499.0|
|Store 1| 44| 432.0|
|Store 2| null| 345.0|
|Store 2| null| 555.0|
|Store 2| 1| 355.0|
|Store 2| 1| 355.0|
|Store 2| 3| 387.0|
|Store 2| 4| 312.0|
| null| null| null|
| null| 10| null|
+-------+-----------+-----------------+