Dataframe 如何将数据帧值转换为Map[String,List[String]]?

Dataframe 如何将数据帧值转换为Map[String,List[String]]?,dataframe,apache-spark,Dataframe,Apache Spark,我想将下面的数据帧转换为Map[String,List[String]]。我已经更改了初始数据框以获取列表格式的名称列(使用collect\u List),但无法将其转换为Map[String,List[String]] 数据帧 +---------+-------+ |City | Name | +---------+-------+ |Mumbai |[A,B] | |Pune |[C,D] | |Delhi |[A,D] | +---------+----

我想将下面的数据帧转换为Map[String,List[String]]。我已经更改了初始数据框以获取列表格式的名称列(使用
collect\u List
),但无法将其转换为
Map[String,List[String]]

数据帧

+---------+-------+
|City     |  Name |
+---------+-------+
|Mumbai   |[A,B]  |
|Pune     |[C,D]  |
|Delhi    |[A,D]  |
+---------+-------+
预期产出:

Map(Mumbai -> List(A,B), Pune -> List(C,D), Delhi-> List(A,D))

您可以转换为rdd并收集为地图,如下所示

val df = Seq(
  ("Mumbai", List("A", "B")),
  ("Pune", List("C", "D")),
  ("Delhi", List("A", "D"))
).toDF("city", "name")

val map: collection.Map[String, List[String]] =  df.rdd
  .map(row => (row.getAs[String]("city"), row.getAs[List[String]]("name")))
  .collectAsMap()
希望这有帮助