regex - 使用正则表达式连接火花中的两个数据帧
问题描述
假设我有一个数据框 df1,其“颜色”列包含一堆颜色,另一个数据框 df2 的“短语”列包含各种短语。
我想加入两个数据框,其中 d1 中的颜色出现在 d2 中的短语中。我不能使用d1.join(d2, d2("phrases").contains(d1("color"))
,因为它会在词组中出现的任何地方加入。例如,我不想匹配像 scaRED 这样的词,其中 RED 是另一个词的一部分。我只想在颜色作为短语中的单独单词出现时加入。
我可以使用正则表达式来解决这个问题吗?当我需要引用表达式中的列时,我可以使用什么函数以及语法如何?
解决方案
没有看到您的数据,但这是一个初学者,有一点变化。据我所知,不需要正则表达式,但谁知道:
// You need to do some parsing like stripping of . ? and may be lowercase or uppercase
// You did not provide an example on the JOIN
import org.apache.spark.sql.functions._
import scala.collection.mutable.WrappedArray
val checkValue = udf { (array: WrappedArray[String], value: String) => array.iterator.map(_.toLowerCase).contains(value.toLowerCase() ) }
//Gen some data
val dfCompare = spark.sparkContext.parallelize(Seq("red", "blue", "gold", "cherry")).toDF("color")
val rdd = sc.parallelize( Array( (("red","hello how are you red",10)), (("blue", "I am fine but blue",20)), (("cherry", "you need to do some parsing and I like cherry",30)), (("thebluephantom", "you need to do some parsing and I like fanta",30)) ))
//rdd.collect
val df = rdd.toDF()
val df2 = df.withColumn("_4", split($"_2", " "))
df2.show(false)
dfCompare.show(false)
val res = df2.join(dfCompare, checkValue(df2("_4"), dfCompare("color")), "inner")
res.show(false)
返回:
+------+---------------------------------------------+---+--------------------------------------------------------+------+
|_1 |_2 |_3 |_4 |color |
+------+---------------------------------------------+---+--------------------------------------------------------+------+
|red |hello how are you red |10 |[hello, how, are, you, red] |red |
|blue |I am fine but blue |20 |[I, am, fine, but, blue] |blue |
|cherry|you need to do some parsing and I like cherry|30 |[you, need, to, do, some, parsing, and, I, like, cherry]|cherry|
+------+---------------------------------------------+---+--------------------------------------------------------+------+
推荐阅读
- r - 表函数如何用于两个向量的组合?
- codeigniter - codeigniter 项目的副本不能在同一台服务器上工作,而是在子域上工作
- mongodb - Spring-data 和 MongoDb 基于子文档属性的聚合和排序
- amazon-athena - 在 athena 上使用 quicksight 是否像普通的 athena 一样每次查询都要花钱?
- javascript - 如何根据对象数组对对象的json数组进行分组
- discord - 在没有公共渠道的情况下写入 Discord 机器人
- webpack - Yarn 努力构建 CSS
- visual-studio - 我为跨平台移动应用程序开发启动了一个新的 Xamarin Forms 项目,并且正在解决问题
- javascript - 除非由 window.location.href 重定向,否则将 URl 设为私有
- build - AOSP R/Q 构建因 clang++ 而失败:错误:clang 前端命令因信号而失败