如何在两个数组列之间找到共同的元素? [英] How to find common elements among two array columns?

查看:87
本文介绍了如何在两个数组列之间找到共同的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个逗号分隔的字符串列(sourceAuthorstargetAuthors).

I have two comma-separated string columns (sourceAuthors and targetAuthors).

val df = Seq(
  ("Author1,Author2,Author3","Author2,Author3,Author1")
).toDF("source","target")

我想添加另一列nCommonAuthors及其常见作者数.

I'd like to add another column nCommonAuthors with the number of common Authors.

我已经尝试通过这种方式做到这一点:

I've tried doing this by this way:

def myUDF = udf { (s1: String, s2: String) =>
  s1.split(",")
  s2.split(",")
  s1.intersect(s2).length
}
val newDF = myDF.withColumn("nCommonAuthors", myUDF($"source", $"target"))

我收到以下错误:

线程"main"中的异常java.lang.UnsupportedOperationException:不支持单元类型的模式

Exception in thread "main" java.lang.UnsupportedOperationException: Schema for type Unit is not supported

知道为什么会出现此错误吗?如何在两列之间找到共同的元素?

Any idea why I get this error? How to find the common elements among two columns?

推荐答案

基于SCouto的答案,我为您提供了适用于我的完整解决方案:

Based on SCouto answer, I give you the complete solution that worked for me:

  def myUDF: UserDefinedFunction = udf(
(s1: String, s2: String) => {
  val splitted1 = s1.split(",")
  val splitted2 = s2.split(",")
  splitted1.intersect(splitted2).length
})

  val spark = SparkSession.builder().master("local").getOrCreate()

  import spark.implicits._

  val df = Seq(("Author1,Author2,Author3","Author2,Author3,Author1")).toDF("source","target")

  df.show(false)

+-----------------------+-----------------------+
|source                 |target                 |
+-----------------------+-----------------------+
|Author1,Author2,Author3|Author2,Author3,Author1|
+-----------------------+-----------------------+

  val newDF: DataFrame = df.withColumn("nCommonAuthors", myUDF('source,'target))

  newDF.show(false)

+-----------------------+-----------------------+--------------+
|source                 |target                 |nCommonAuthors|
+-----------------------+-----------------------+--------------+
|Author1,Author2,Author3|Author2,Author3,Author1|3             |
+-----------------------+-----------------------+--------------+

这篇关于如何在两个数组列之间找到共同的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆