转换阵列>类型 在阶

问题描述 投票:-3回答:2

我面临的问题,在我的数据帧转换列字符串格式。数据帧的例子如下:

-- example_code_b: string (nullable = true)
-- example_code: array (nullable = true)
[info]  |    |-- element: map (containsNull = true)
[info]  |    |    |-- key: string
[info]  |    |    |-- value: string (valueContainsNull = true)

我想转换example code从当前(string,string) array(map(string,string))格式。

输入是在[Map(entity -> PER), Map(entity -> PER)]的形式,我想输出是在PER,PER的形式

scala apache-spark dataframe rdd
2个回答
1
投票

你可以做一个UDF在数据帧API或使用数据集的API来做到这一点:

import spark.implicits._

df
  .as[Seq[Map[String,String]]]
  .map(s => s.reduce(_ ++ _))
  .toDF("example_code")
  .show()

请注意,这不考虑多个按键的情况下,他们没有“合并”,但只是覆盖


1
投票

可以简单地使用explode功能上的任何阵列列,这会为阵列的每个值创建单独的行。

val newDF = df.withColumn("mymap" explode(col("example_code")))
© www.soinside.com 2019 - 2024. All rights reserved.