[英]Converting a dataframe into a hashmap where Key is int and Value is a list in Scala
我有一個看起來像這樣的數據框:
鑰匙 | 字 |
---|---|
1 | ['一個測試'] |
2 | ['你好呀] |
我想創建以下哈希圖:
Map(1 -> ['a', 'test'], 2 -> ['hi', 'there'])
但是我不知道如何做到這一點,有人可以幫助我嗎?
謝謝!
必須有幾十種方法來做到這一點。 一種是:
df.collect().map { case row => (row.getAs[Int](0) -> row.getAs[mutable.WrappedArray[String]](1))}.toMap
這與此問題中的解決方案非常相似。 下面應該給你你想要的輸出。 它將所有地圖收集為一個集合,然后使用 UDF 創建單個地圖。 這伴隨着關於 UDF 函數潛在性能不佳的常見警告。
import org.apache.spark.sql.functions.{col, map, collect_list, lit}
import org.apache.spark.sql.functions.udf
val joinMap = udf { values: Seq[Map[Int, Seq[String]]] =>
values.flatten.toMap
}
val df = Seq((1, Seq("a", "test")), (2, Seq("hi", "there"))).toDF("key", "words")
val rDf = df
.select(lit(1) as "id", map(col("key"), col("words")) as "kwMap")
.groupBy("id")
.agg(collect_list(col("kwMap")) as "kwMaps")
.select(joinMap(col("kwMaps")) as "map")
rDf.show
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.