scala - 在 Scala 中将数据帧转换为 Map 时出现编译器错误
问题描述
我正在尝试将以下数据框:chunkMeta 转换为 scala 中的 Map:
tablename Code
table1 432
table2 567
table3 987
scala> val dataMap = chunkMeta.select($"tablename", $"code".cast("long")).as[(String, Long)].collect.toMap
如果我打印上面的地图,我可以看到数据:
scala> dataMap.foreach(println) => (table1,432)(table2,567)(table3,987)
但是当我在 IntelliJ IDEA 上将相同的数据帧转换为 Map 时,编译器给了我一个错误:
Cannot resolve overloaded method 'select'
构建.sbt:
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"org.apache.spark" %% "spark-core" % "2.0.0" % "provided",
"org.apache.spark" %% "spark-sql" % "2.0.0" % "provided",
"org.json4s" %% "json4s-jackson" % "3.2.11" % "provided",
"org.apache.httpcomponents" % "httpclient" % "4.5.3"
)
// https://mvnrepository.com/artifact/org.postgresql/postgresql
libraryDependencies += "org.postgresql" % "postgresql" % "42.1.4"
我不明白为什么相同的语句适用于 scala REPL 但不适用于 IntelliJ。有没有更好的方法将数据框转换为 Map ?或者这是 scala 编译器的错误?
解决方案
您可以使用map
函数来操作数据框对象。
像下面这样的东西应该可以工作。
import spark.implicits._
val chunkMeta = Seq(("table1",432),
("table2",567),
("table3",987),
("table1",789)).
toDF("tablename", "Code").toDF()
chunkMeta.show()
+---------+----+
|tablename|Code|
+---------+----+
| table1| 432|
| table2| 567|
| table3| 987|
| table1| 789|
+---------+----+
chunkMeta.printSchema()
root
|-- tablename: string (nullable = true)
|-- Code: integer (nullable = false)
val df2 = chunkMeta.map(r => (r.getString(0),r.getInt(1)))
df2.printSchema()
root
|-- _1: string (nullable = true)
|-- _2: integer (nullable = false)
val map1 = df2.collect().toMap
map1.foreach(println)
(table1,789)
(table2,567)
(table3,987)
推荐阅读
- java - 当我们创建具有不同选项的可运行 jar 时,JVM 类加载器序列/副作用是什么?
- javascript - 如何通过 sequelize 获取用户角色?
- excel - 如何将一列中的值与第二列中的每个值连接起来?
- maven - 可以在 Jenkins 中基于每个作业配置 git
- python - 蟒蛇,tkinter。使用 if 语句填充组合框
- linux - 更改目录并允许并行作业一次失败
- javascript - 是否可以从 WordPress 模板 PHP 文件更改 script.js 文件中的 JS 字符串变量?
- java - Java 中的 Mongoid 本地化字段功能
- javascript - Discord Bot 在 dm 中提及用户
- php - Verify hashed passwords using PHP from a MySQL database