【问题标题】:Transpose dataframe withe many columns转置具有多列的数据框
【发布时间】:2019-02-15 11:35:56
【问题描述】:

这是我的数据框架构:

 `root
 |-- customerid: string (nullable = true)
 |-- event: string (nullable = true)
 |-- groupe1: string (nullable = false)
 |-- groupe2: string (nullable = false)
 |-- groupe3: string (nullable = false)

这是我的数据框的一部分

+----------------+--------+--------------------+--------------+----------------+
|customerid|     |  event | group1             | group2       |    groupe3     |
+----------------+--------+--------------------+--------------+----------------+
|     4454545    |        |[aaa,0,0,0]         |[555,0,88,0,0]| [3190,0,0,0,0] |
|     8878787787 |2019    |[bbb,0,fff,0,0]     | [420,0,0,0,0]| [9580,0,0,0,0] |
|     12555888888|2019    |[cccc,0,fff,eee,0]  | [385,0,0,0,0]| [4995,0,0,0,0] |
+----------------+--------------------+--------------------+-------------------+

我试过这段代码:

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($"groupe1", $"groupe2",$"groupe3"))).select(
   $"customerid", $"event",
   $"vars._1".alias("groupe1"), $"vars._2".alias("groupe2"),$"vars._2".alias("groupe3"))

我收到了这个错误:

cannot resolve 'UDF(groupe1, groupe2, groupe3)' due to data type mismatch: argument 1 requires array<string> type, however, '`groupe1`' is of string type. argument 2 requires array<string> type, however, '`groupe2`' is of string type. argument 3 requires array<string> type, however, '`groupe3`' is of string type.;;

【问题讨论】:

    标签: scala apache-spark bigdata


    【解决方案1】:

    列 group1,group2,group3 的类型是字符串,所以它与您的带有 Seq[string] 参数的 udf 不兼容。也许您应该将 udf 的输入更改为字符串类型。

    【讨论】:

    • 我更改为 val zip = udf((xs: String, ys: String, zs: String) => (xs, ys, zs).zipped.toSeq) 但我收到了这个错误 java.util. lang.UnsupportedOperationException:不支持 Char 类型的架构
    • 将输入类型改为字符串后,变量xs,ys,zs现在是字符串,不支持对字符串元组(xs,ys,zs)使用压缩操作,所以,我猜你需要在对它们的元组使用 zipped 之前将 xs、ys、zs 拆分为 seq。
    • 喜欢这个? : val df4=df.withColumn("vars", explode(zip((split($"groupe1",","), (split($"groupe3",","),(split($"groupe2", ",")))).select( $"customerid", $"event", $"vars._1".alias("groupe1"), $"vars._2".alias("groupe3"),$" vars._2".alias("groupe2"))
    • 是的,这是一个选项。您也可以像这样更改 udf:(xs.split(“,”),ys.split(“,”),zs.split(“, ”)).zipped.toSeq
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2017-01-20
    • 2021-05-12
    • 2020-06-03
    • 2022-06-14
    相关资源
    最近更新 更多