[英]Scala Spark Dataframe: how to explode an array of Int and array of struct at the same time
[英]How to filter a spark's dataframe array with scala
我是Scala的初学者。
我有2列的数据框:
第一个是日期,第二个是单词数组。
created_at:string
words:array
element:string
我只想保留以“#”开头的单词
我更喜欢在分解数组之前进行过滤,因为大多数单词不是以“#”开头
我没有找到修改数组列和应用类似filter(_。startsWith(“#”))之类的方法。
可能吗 ? 如何 ?
谢谢
皮埃尔
您可以创建一个简单的UDF来从数组列中过滤掉不需要的单词:
val df = Seq(
("2018-05-01", Seq("a", "#b", "c")),
("2018-05-02", Seq("#d", "#e", "f"))
).toDF("created_at", "words")
def filterArray = udf( (s: Seq[String]) =>
s.filterNot(_.startsWith("#"))
)
df.select($"created_at", filterArray($"words")).show
// +----------+----------+
// |created_at|UDF(words)|
// +----------+----------+
// |2018-05-01| [a, c]|
// |2018-05-02| [f]|
// +----------+----------+
试试这个:
import org.apache.spark.sql.functions._
df.select(explode(col("words")).as("word"), col("created_at")).
where("word LIKE '#%'").
groupBy(col("created_at")).
agg(collect_set(col("word")).as("words")).
show
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.