scala - 从列表中搜索数据框以及在 Scala 的新列中找到的所有元素
问题描述
我有一个 df,我需要搜索关键字列表中是否有任何元素集.. 如果是,我需要将所有这些关键字 @ 分隔在一个名为 found 或 not 的新列中。
我的df就像
utid | description
123 | my name is harry and I live in newyork
234 | my neighbour is daniel and he plays hockey
该列表非常大,例如 list ={harry,daniel,hockey,newyork}
输出应该像
utid | description | foundornot
123 | my name is harry and I live in newyork | harry@newyork
234 | my neighbour is daniel and he plays hockey | daniel@hockey
该列表非常大,例如一些 20k 关键字 ..如果找不到打印 NF
解决方案
您可以检查list
if exists 函数中每一行列中description
的udf
元素,并将元素列表作为由@分隔的字符串以将其返回,否则将NF字符串作为
val list = List("harry","daniel","hockey","newyork")
import org.apache.spark.sql.functions._
def checkUdf = udf((strCol: String) => if (list.exists(strCol.contains)) list.filter(strCol.contains(_)).mkString("@") else "NF")
df.withColumn("foundornot", checkUdf(col("description"))).show(false)
这应该给你
+----+------------------------------------------+-------------+
|utid|description |foundornot |
+----+------------------------------------------+-------------+
|123 |my name is harry and i live in newyork |harry@newyork|
|234 |my neighbour is daniel and he plays hockey|daniel@hockey|
+----+------------------------------------------+-------------+
推荐阅读
- kerberos - 从 shellscript 存储/检索 kinit 密码
- javascript - 如何在 vue js 中获取 aria-rowindex 值?
- terraform - Terraform VPN - 隧道选项
- javascript - Plumier - 在自定义验证中访问时参数属性为 null
- python - Tensorflow RuntimeError:尝试使用关闭的会话
- amazon-web-services - 如何在状态机中指定资源 ARN(Amazon 资源名称)
- mysql - 运行sql文件后,Win10 MySQL CPU 100%
- c++ - 哪个优先,自由函数 operator==() 或成员函数 operator==()?
- java - 来自 Observable 的对象
使用 subscribe() 不打印值 - python - 将此损失函数方程转换为python代码