scala - 带 3 个参数的 zip 函数
问题描述
我想在 Spark SQL 表中转置多列
我发现这个解决方案只有两列,我想知道如何使用三列的 zip 函数varA, varB and varC.
import org.apache.spark.sql.functions.{udf, explode}
val zip = udf((xs: Seq[Long], ys: Seq[Long]) => xs.zip(ys))
df.withColumn("vars", explode(zip($"varA", $"varB"))).select(
$"userId", $"someString",
$"vars._1".alias("varA"), $"vars._2".alias("varB")).show
这是我的数据框架构:
`root
|-- owningcustomerid: string (nullable = true)
|-- event_stoptime: string (nullable = true)
|-- balancename: string (nullable = false)
|-- chargedvalue: string (nullable = false)
|-- newbalance: string (nullable = false)
`
我试过这段代码:
val zip = udf((xs: Seq[String], ys: Seq[String], zs: Seq[String]) => (xs, ys, zs).zipped.toSeq)
df.printSchema
val df4=df.withColumn("vars", explode(zip($"balancename", $"chargedvalue",$"newbalance"))).select(
$"owningcustomerid", $"event_stoptime",
$"vars._1".alias("balancename"), $"vars._2".alias("chargedvalue"),$"vars._2".alias("newbalance"))
我收到了这个错误:
cannot resolve 'UDF(balancename, chargedvalue, newbalance)' due to data type mismatch: argument 1 requires array<string> type, however, '`balancename`' is of string type. argument 2 requires array<string> type, however, '`chargedvalue`' is of string type. argument 3 requires array<string> type, however, '`newbalance`' is of string type.;;
'项目 [owningcustomerid#1085,event_stoptime#1086,balancename#1159,chargedvalue#1160,newbalance#1161,explode(UDF(balancename#1159,chargedvalue#1160,newbalance#1161))AS vars#1167]
解决方案
一般来说,在 Scala 中,您可以使用Tuple3.zipped
val zip = udf((xs: Seq[Long], ys: Seq[Long], zs: Seq[Long]) =>
(xs, ys, zs).zipped.toSeq)
zip($"varA", $"varB", $"varC")
特别是在 Spark SQL (>= 2.4) 中,您可以使用arrays_zip
函数:
import org.apache.spark.sql.functions.arrays_zip
arrays_zip($"varA", $"varB", $"varC")
但是您必须注意,您的数据不包含array<string>
但很简单- 因此不允许使用strings
Spark或爆炸,您应该首先解析您的数据。arrays_zip
推荐阅读
- java - IOError:尝试在 java 中使用 jython 时出现 FileNotFound
- c++ - 在并行算法中使用 range::view::iota
- c# - 使用 SignalR 找不到名称为“x”的客户端方法
- javascript - 从文本字符串中选择多个关键字
- java - Java 用 ArrayList 和嵌套的 For 循环打印出一副卡片
- php - 无法通过 php 检索 jquery 设置值
- rx-java2 - RxAndroid:如何在 Observer 和 Observable 中添加额外的方法
- python - 如何根据熊猫数据框中的非连续索引列表替换值?
- php - ZF3 - 使用模块目录外部的部分
- html - Bootstrap 4 - 如何使列拉伸到父级的高度?