【问题标题】:Spark: apply sliding() to each row without UDFSpark:将滑动()应用于没有UDF的每一行
【发布时间】:2020-11-05 03:50:14
【问题描述】:

我有一个包含几列的数据框。第 i 列包含字符串。我想将字符串 sliding(n) 函数应用于列中的每个字符串。有没有办法在不使用用户定义函数的情况下做到这一点?

示例: 我的数据框是

var df = Seq((0, "hello"), (1, "hola")).toDF("id", "text")

我想对"text"列的每个元素应用sliding(3)函数,得到对应的dataframe

Seq(
    (0, ("hel", "ell", "llo"))
    (1, ("hol", "ola"))
)

我该怎么做?

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    对于 spark 版本 >= 2.4.0,这可以使用内置函数 array_repeattransformsubstring 来完成。

    import org.apache.spark.sql.functions.{array_repeat, transform, substring}
    
    //Repeat the array `n` times
    val repeated_df = df.withColumn("tmp",array_repeat($"text",length($"text")-3+1))
    //Get the slices with transform higher order function
    val res = repeated_df.withColumn("str_slices",
                                     expr("transform(tmp,(x,i) -> substring(x from i+1 for 3))")
                                    )
    //res.show()
    +---+-----+---------------------+---------------+
    |id |text |tmp                  |str_slices     |
    +---+-----+---------------------+---------------+
    |0  |hello|[hello, hello, hello]|[hel, ell, llo]|
    |1  |hola |[hola, hola]         |[hol, ola]     |
    +---+-----+---------------------+---------------+
    

    【讨论】:

    • 非常感谢!如果现在我想对 str_slices 列中的每个子字符串应用一个函数(例如 hash())怎么办?
    猜你喜欢
    • 1970-01-01
    • 2022-01-27
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多