Groupby根据先前可用值和下一个可用值的平均值填充dataframe中缺少的值

2024-04-20 07:57:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,它有一些组,我想根据分数列的上一个可用值和下一个可用值平均值来填充缺少的值,即(上一个值+下一个值)/2

我想按州、学校、班级、科目分组,然后填入值

如果分数列中第一个值不可用,则用下一个或多个可用值填充该值 如果最后一个值不可用,则用以前可用的值填充该值 对于每个组,都需要遵循这一点

这是一个数据插补的复杂问题。我在网上搜索发现熊猫有一些功能,比如。 pandas.core.groupby.DataFrameGroupBy.ffill但不知道如何在这种情况下使用

我想用python、pyspark、SQL来解决这个问题

我的数据框看起来像这样

Missing values

Data Imputation


Tags: 数据core功能pandassql情况分数学校
1条回答
网友
1楼 · 发布于 2024-04-20 07:57:45

也许这是有帮助的-

加载测试数据

df2.show(false)
    df2.printSchema()
    /**
      * +  -+  -+
      * |class|score|
      * +  -+  -+
      * |A    |null |
      * |A    |46   |
      * |A    |null |
      * |A    |null |
      * |A    |35   |
      * |A    |null |
      * |A    |null |
      * |A    |null |
      * |A    |46   |
      * |A    |null |
      * |A    |null |
      * |B    |78   |
      * |B    |null |
      * |B    |null |
      * |B    |null |
      * |B    |null |
      * |B    |null |
      * |B    |56   |
      * |B    |null |
      * +  -+  -+
      *
      * root
      * |  class: string (nullable = true)
      * |  score: integer (nullable = true)
      */

从分数列中输入空值(检查新的分数列)


    val w1 = Window.partitionBy("class").rowsBetween(Window.unboundedPreceding, Window.currentRow)
    val w2 = Window.partitionBy("class").rowsBetween(Window.currentRow, Window.unboundedFollowing)
    df2.withColumn("previous", last("score", ignoreNulls = true).over(w1))
      .withColumn("next", first("score", ignoreNulls = true).over(w2))
      .withColumn("new_score", (coalesce($"previous", $"next") + coalesce($"next", $"previous")) / 2)
      .drop("next", "previous")
      .show(false)

    /**
      * +  -+  -+    -+
      * |class|score|new_score|
      * +  -+  -+    -+
      * |A    |null |46.0     |
      * |A    |46   |46.0     |
      * |A    |null |40.5     |
      * |A    |null |40.5     |
      * |A    |35   |35.0     |
      * |A    |null |40.5     |
      * |A    |null |40.5     |
      * |A    |null |40.5     |
      * |A    |46   |46.0     |
      * |A    |null |46.0     |
      * |A    |null |46.0     |
      * |B    |78   |78.0     |
      * |B    |null |67.0     |
      * |B    |null |67.0     |
      * |B    |null |67.0     |
      * |B    |null |67.0     |
      * |B    |null |67.0     |
      * |B    |56   |56.0     |
      * |B    |null |56.0     |
      * +  -+  -+    -+
      */

相关问题 更多 >