我有一个如下所示的数据集:
val df = Seq(("beatles", Seq(Seq("help", "hey jude"))),
("romeo", Seq(Seq("help2", "hey judge"),Seq("help3", "they judge")))).toDF("col1", "col2")
root
|-- col1: string (nullable = true)
|-- col2: array (nullable = true)
| |-- element: array (containsNull = true)
| | |-- element: string (containsNull = true)
我想在数据hasHitSong
框中添加一列,它将迭代 col2 下的热门歌曲序列,检查是否存在热门歌曲,例如。“嘿裘德”并将其标记为 1,否则标记为 0。
| col1 | col2 | hasHitSongs |
|---------|-------------------------------------------------|-------------|
| beatles | ["help", "hey jude"] | 1 |
| romeo | [["help2", "hey judge"],["help3", "hey judge"]] | 0 |
有没有办法在不爆炸列 col2 并且只迭代 col2 下的嵌套数组的情况下执行此操作?
如果您使用的是 spark 2.4 或更高版本:
使用内置函数
df.withColumn("hasHitSongs", array_contains(flatten(col("col2")), "hey jude"))
使用高阶函数
df.withColumn("hasHitSongs, expr("exists(col2, a -> exists(a, b -> b = 'hey jude'))"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句