我正在尝试获取 DataFrame
的单列的不同值(称为: df
)放入与列的数据类型匹配的数组中。这是我尝试过的方法,但不起作用:
def distinctValues[T: ClassTag](column: String): Array[T] = {
df.select(df(column)).distinct.map {
case Row(s: T) => s
}.collect
}
该方法位于隐式类内部,因此调用 df.distinctValues("some_col")
给我:
scala.MatchError: [ABCD] (of class org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema)
有没有一种优雅的方式来实现我想要的,而且类型安全?
我使用的是 Spark 1.4.1。
最佳答案
问题是您使用的是模式匹配而不是 getAs
方法:
implicit final class DataFrameOps(val df: DataFrame) {
def distinctValues[T: ClassTag](column: String): Array[T] = {
df.select(column).distinct().map(_.getAs[T](column)).collect()
}
}
用法:
val ageArray: Array[Int] = df.distinctValues("age")
or
val ageArray = df.distinctValues[Int]("age")
关于scala - 从 DataFrame 到 Array 的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37294227/