scala - 如何获取 Dataframe 上的所有数组名称
问题描述
如何获取 Dataframe 上的所有数组名称?
问题是我试图爆炸所有阵列。
import org.apache.spark.sql.{Column, DataFrame, SparkSession}
import org.apache.spark.sql.functions.col
import org.apache.spark.sql.types.{ArrayType, StructField, StructType}
val providersDF=SIWINSDF.select(explode(col("**providers**")).as("collection")).select(col("collection.*"))
def flattenSchema(schema: StructType, prefix: String = null) : Array[Column] = {
schema.fields.flatMap(f => {
val colName = if (prefix == null) f.name else (prefix + "." + f.name)
f.dataType match {
case st: StructType => flattenSchema(st, colName)
case _ => Array(col(colName).alias(colName))
}
})
}
val newDF=providersDF.select(flattenSchema(providersDF.schema):_*)
newDF.toDF(newDF.columns.map(_.replace(".", "_")): _*).printSchema
要获取我想做的所有数组名称:
获取我正在做的名称 df.schema.filter(st => st.dataType.isInstanceOf[ArrayType]).flatMap(.dataType.asInstanceOf[StructType].fields).map(.name)
任何帮助表示赞赏。
解决方案
ArrayType
这是一个从 DataFrame中提取所有嵌套列的递归方法:
import org.apache.spark.sql.types._
def extractArrayCols(schema: StructType, prefix: String): Seq[String] =
schema.fields.flatMap {
case StructField(name, struct: StructType, _, _) => extractArrayCols(struct, prefix + name + ".")
case StructField(name, ArrayType(_, _), _, _) => Seq(s"$prefix$name")
case _ => Seq.empty[String]
}
测试方法:
import org.apache.spark.sql.functions._
case class W(u: Int, v: Seq[String])
val df = Seq(
(10, Seq(1, 2), W(1, Seq("a", "b"))),
(20, Seq(3), W(2, Seq("c", "d")))
).toDF("c1", "c2", "c3")
val arrayCols = extractArrayCols(df.schema, "")
// arrayCols: Seq[String] = ArraySeq(c2, c3.v)
推荐阅读
- python - 在 python pandas 数据框中分配循环以提高性能
- jasper-reports - 在通过 Jrxml 模板生成的 Pdf 中获取空格而不是文本
- android - NDK SurfaceView 重绘在屏幕旋转时显示损坏
- r - 如何在 $ 之前和之后将“i”放在循环中
- spring - 迁移现有 Spring Websocket 处理程序以使用 rsocket
- ansible - 如何在保留键名上使用 Jinja2 过滤器?
- sql - TOAD for Oracle 错误地返回一周前的数据
- python - 根据其他列创建指示特定值历史存在的列
- ansible - 如何使用ansible获取远程机器的主机名并在配置文件中设置
- module - 层配置模块路由