You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中将DataFrame转换为键为整数、值为列表的哈希映射的方法

实现方案

Python Pandas 场景

直接调用set_index+to_dict组合方法即可:

# 假设你的原始DataFrame变量名为df
hash_map = df.set_index('key')['words'].to_dict()

运行后得到的hash_map结构为{1: ['a', 'test'], 2: ['hi', 'there']},Python字典本身就是哈希映射实现,和你需要的Map结构逻辑完全一致。

Scala Spark 场景

如果是Spark DataFrame要转换为Scala原生Map,可按如下方式实现:

// 假设你的原始DataFrame变量名为df
val hashMap = df.select("key", "words")
  .collect()
  .map(row => row.getAs[Int]("key") -> row.getAs[Seq[String]]("words"))
  .toMap

运行后得到的结果为Map(1 -> List(a, test), 2 -> List(hi, there)),完全匹配需求。


内容的提问来源于stack exchange,提问作者Dewi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:09:03