scala - 将列表项映射到 org.apache.spark.sql.Column 类型

标签 scala apache-spark

我正在尝试对 org.apache.spark.sql.DataFrame 类型的 Dataframe 中的列列表进行求和,并创建一个新列“sums”和数据帧“out”。

如果我手动列出列,我可以很容易地做到这一点,例如,这有效

val columnsToSum = List(col("led zeppelin"), col("lenny kravitz"), col("leona lewis"), col("lily allen"))
val out = df3.withColumn("sums", columnsToSum.reduce(_ + _))

但是,如果我希望通过直接从数据帧中提取列名称来实现此目的,则列表对象中的项目不相同,并且我无法执行此操作,例如

val columnsToSum = df2.schema.fields.filter(f => f.dataType.isInstanceOf[StringType]).map(_.name).patch(0, Nil, 1).toList // arrays are mutable (remove "user" from list)
println(tmpArr)
>> List(a perfect circle, abba, ac/dc, adam green, aerosmith, afi, ...

// Trying the same method
val out = df3.withColumn("sums", columnsToSum.reduce(_ + _))

>> found   : String
 required: org.apache.spark.sql.Column
val out = df3.withColumn("sums", tmpArr.reduce(_ + _))found   : String
 required: org.apache.spark.sql.Column
val out = df3.withColumn("sums", tmpArr.reduce(_ + _))

如何进行这种类型的转换?我试过:

List(a perfect circle, abba, ac/dc, ...).map(_.Column)
List(a perfect circle, abba, ac/dc, ...).map(_.spark.sql.Column)
List(a perfect circle, abba, ac/dc, ...).map(_.org.apache.spark.sql.Column)

哪个没用 提前致谢

最佳答案

您可以使用函数 col 从字符串中获取列对象(您实际上已经在第一个代码片段中使用了它)。

所以这应该有效:

columnsToSum.map(col).reduce(_ + _)

或移动详细版本:

columnsToSum.map(c => col(c)).reduce(_ + _)

关于scala - 将列表项映射到 org.apache.spark.sql.Column 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65003510/

相关文章:

scala - 使用 sc.union 时 Spark 堆栈溢出错误

scala - 为什么 Spray-can 服务器不响应 http 请求?

scala - 根据发送的消息在 Akka Ask 上恢复

hadoop - 我可以在Spark中创建序列文件吗?

apache-spark - 在 Spark sql 中计数以检查查询是否返回空结果的替代方法

python - PySpark - 将单个整数列表与列表列进行比较

java - Spark DataFrame如何使用java获取最新的n行

scala - 为什么这个 LR 代码在 spark 上运行太慢?

scala - free monad 和 AST 的关系

class - Scala 中符号的导入和通配符导入