我有一个列表,其中有几个人参加:
val list = Seq("Car", "House", "Beach")
数据如下所示:
val df = spark.sparkContext.parallelize(Seq(
("Pete", "He has a Car"),
("Mike", "The Beach is beautiful"),
("Steve", "Look at this House")
)).toDF("Name", "message"
我想要完成的是一个额外的列,如果元素出现在消息列中,则值是列表的元素。
|----------------------------------|
|Name |Message |NewCol|
|----------------------------------|
|Pete |He has a Car |Car |
|Mike |The Beach is beatiful|Beach |
|Steve|Look at this House |House |
|----------------------------------|
我尝试了一些但没有任何成功的事情,比如
a) when($"message".isin(list:_*)
b) A udf with -> list.exists(message.contains(_))
我还考虑过将字符串与正则表达式*<listelement>*
进行比较,但无法使其工作。
由于列表是由数据帧的列创建的,因此加入也是可能的(甚至更需要)。新列仅用于事后与列表的原点df连接。
val new_df = df.join(df_listorigin, Seq("NewCol"))
我觉得现在我觉得太复杂了。任何帮助或想法将不胜感激。
答案 0 :(得分:2)
UDF的方法:
val contains = udf((m:String) => list.filter(m.contains(_)).mkString(","))
df
.withColumn("NewCol",contains($"message"))
.show()
+-----+--------------------+------+
| Name| message|NewCol|
+-----+--------------------+------+
| Pete| He has a Car| Car|
| Mike|The Beach is beau...| Beach|
|Steve| Look at this House| House|
+-----+--------------------+------+
或者加入:
df
.join(list.toDF("NewCol"),$"message".contains($"NewCol"),"left")
.show()
+-----+--------------------+------+
| Name| message|NewCol|
+-----+--------------------+------+
| Pete| He has a Car| Car|
| Mike|The Beach is beau...| Beach|
|Steve| Look at this House| House|
+-----+--------------------+------+