【问题标题】:Fill Null values with mean of previous rows用前几行的平均值填充 Null 值
【发布时间】:2020-03-25 17:27:42
【问题描述】:

这是我的示例数据:

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))

【问题讨论】:

  • 嘿阿舒,你能告诉我们你尝试了什么吗?现在,您的问题给人的印象是您只是希望这里的人们会为您编写代码。你看过窗口函数吗?
  • 更新了问题,请看

标签: python dataframe apache-spark pyspark


【解决方案1】:

您的解决方案是朝着正确方向迈出的一步(即使您没有显示已添加的列)。您需要在窗口中按月份和日期进行分区,按日期列(基本上按年份)对结果窗口进行排序,然后将窗口限制为所有前面的行。像这样:

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)))
          )

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 2019-09-02
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2018-06-02
    • 2021-10-25
    • 2022-01-16
    • 2019-03-31
    相关资源
    最近更新 更多