【问题标题】:How to populate last not null data into column?如何将最后一个非空数据填充到列中?
【发布时间】:2019-10-10 21:48:40
【问题描述】:

我的输入 DataFrame 如下所示

+-------+
|Column1|
+-------+
|FILE_1 |
|11     |
|12     |
|212    |
|FILE_2 |
|1213   |
|13312  |
|4124   |
+-------+

在输入DataFrameFILE_*是文件名,FILE_下面的数据是它的内容。

例如,FILE_1 有 11,12,212 个内容。

我想将新列添加到现有的 Input DataFrame 中,这给了我文件名及其内容的这种关系,如下所示:

+-------+-------+
|Column1|Column2|
+-------+-------+
|FILE_1 |FILE_1 |
|11     |FILE_1 |
|12     |FILE_1 |
|212    |FILE_1 |
|FILE_2 |FILE_2 |
|1213   |FILE_2 |
|13312  |FILE_2 |
|4124   |FILE_2 |
+-------+-------+

【问题讨论】:

标签: scala dataframe apache-spark


【解决方案1】:

这是一种方法:

import org.apache.spark.sql.functions.{last, when}
import org.apache.spark.sql.expressions.Window

    val df = Seq("FILE_1","11","12","212","FILE_2","1213","3312","4124").toDF("column1")
    val w = Window.rowsBetween(Window.unboundedPreceding, 0)
    val df2 = df.withColumn("tmp", when($"column1".startsWith("FILE_"), $"column1").otherwise(null))
      .withColumn("column2", last($"tmp", true).over(w)).drop("tmp")

The result looks something like that

通过this great Databricks post.获取有关 Spark Window 的更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-22
    • 2019-11-21
    • 1970-01-01
    • 2021-10-25
    • 2015-09-17
    • 2017-07-19
    • 2019-10-01
    • 2020-11-28
    相关资源
    最近更新 更多