我正在尝试获取值大于2的记录的百分比。
代码如下:
val seq = Seq(0, 1, 2, 3)
val scores = seq.toDF("value")
我可以使用以下步骤来实现。
val totalCnt = scores.count()
val morethan2 : Long = scores.filter(col("value") > 2).count()
val percent = morethan2.toFloat/totalCnt;
println(" percent is " + percent)
但是,最好的/优化的方法是使它在单个语句中起作用, 可能使用聚合函数?
答案 0 :(得分:0)
您将至少需要进行一次汇总。像这样的东西。
val seq = Seq(0, 1, 2, 3)
val scores = seq.toDF("value")
.withColumn("all", lit(1))
.withColumn("morethan2", when(col("value") > 2, lit(1)).otherwise(lit(0)))
.agg(sum(col("all")).as("count"), sum(col("morethan2")).as("morethan2count"))
.withColumn("percent", col("morethan2count") / col("count"))
val percent = scores.take(1)(0).getAs[Double]("percent")
希望对您有帮助。