scala - Spark Dataframe - 获取所有对列表(Scala)
问题描述
我有以下情况:我有一个以“数组”作为架构的数据框。现在我想为每个数组获取所有对列表并将其再次保存在数据框中。例如:
这是原始数据框:
+---------------+
| candidateList|
+---------------+
| [1, 2]|
| [2, 3, 4]|
| [1, 3, 5]|
|[1, 2, 3, 4, 5]|
|[1, 2, 3, 4, 5]|
+---------------+
这就是计算后的样子:
+---------------+
| candidates |
+---------------+
| [1, 2]|
| [2, 3]|
| [2, 4]|
| [3, 4]|
| [1, 3]|
| [1, 5]|
| [3, 5]|
|and so on... |
+---------------+
我真的不知道这在火花中是如何实现的,也许有人给我一个小费。
亲切的问候
解决方案
您需要创建一个 UDF(用户定义函数)并将其与explode
函数一起使用。由于 Scala 集合的combinations
方法,UDF 本身很简单:
import scala.collection.mutable
import org.apache.spark.sql.functions._
import spark.implicits._
val pairsUdf = udf((arr: mutable.Seq[Int]) => arr.combinations(2).toArray)
val result = df.select(explode(pairsUdf($"candidateList")) as "candidates")
result.show(numRows = 8)
// +----------+
// |candidates|
// +----------+
// | [1, 2]|
// | [2, 3]|
// | [2, 4]|
// | [3, 4]|
// | [1, 3]|
// | [1, 5]|
// | [3, 5]|
// | [1, 2]|
// +----------+
推荐阅读
- node.js - 如何使用密码在neo4j中循环对象
- javascript - 如何将特定属性转换为集合数据结构
- apache-kafka - 架构注册表只读副本
- rabbitmq - RabbitMQ 在 Debian 上从 3.8.2 升级到 3.8.6 -- 如何安装最新版本?
- reactjs - 如何将 HTML 元素传递给反应组件?
- c++ - if(x % y == 0) 导致我的程序不输出任何东西?
- python - Python index/lineno 用于使用检查调用 expr 的 ast
- reactive-programming - 具有多个数据库(MySQL、MongoDB)的反应式全局事务
- javascript - wordpress ajax 请求为超过 1mb 的数据返回 'POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED'
- docker - 在 VS Code 中连接到远程 Docker 容器