簡體   English   中英

用前幾行的平均值填充 Null 值

[英]Fill Null values with mean of previous rows

這是我的示例數據:

date,number
2018-06-24,13
2018-06-25,4
2018-06-26,5
2018-06-27,1
2017-06-24,3
2017-06-25,5
2017-06-26,2
2017-06-27,null
2016-06-24,3
2016-06-25,5
2016-06-26,2
2016-06-27,7
2015-06-24,8
2015-06-25,9
2015-06-26,12
2015-06-27,13

我需要用前一年數據的平均值填充空值。 也就是說,如果'2017-06-27'是空值,我需要用"2016-06-27"'2015-06-27'數據的平均值來填充它。

輸出

date,number
2018-06-24,13
2018-06-25,4
2018-06-26,5
2018-06-27,1
2017-06-24,3
2017-06-25,5
2017-06-26,2
2017-06-27,10
2016-06-24,3
2016-06-25,5
2016-06-26,2
2016-06-27,7
2015-06-24,8
2015-06-25,95
2015-06-26,12
2015-06-27,13

我使用了下面的代碼,但它讓我了解了特定分區中的所有內容。

提取的日期和月份列

wingrp = Window.partitionBy('datee','month')
df = df.withColumn("TCount",avg(df["Count"]).over(wingrp))

您的解決方案是朝着正確方向邁出的一步(即使您沒有顯示已添加的列)。 您需要在窗口中按月份和日期進行分區,按日期列(基本上按年份)對生成的窗口進行排序,然后將窗口限制為所有前面的行。 像這樣:

from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql.window import Window

schema = StructType([
    StructField("date", DateType(), True),
    StructField("number", IntegerType(), True)
])

df = spark.read.csv("your_data.csv",
                    header=True,
                    schema=schema)

wind = (Window
        .partitionBy(month(df.date), dayofmonth(df.date))
        .orderBy("date")
        .rowsBetween(Window.unboundedPreceding, Window.currentRow)
        )

result = (df
          .withColumn("result",
                      coalesce(df.number, avg(df.number).over(wind)))
          )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM