我想获取Spark中数据框每一列的最大值。我的代码仅适用于一列(例如第一列):
val col = df.columns(0);
val Row(maxValue: Int) = df.agg(max(col)).head();
我不知道如何组合foreach
以及我拥有的代码,这样我才能为数据帧中的每一列获取最大值。(我不知道数据框中有多少列,列名是什么)
谢谢。
foreach
很少,当你想将有用的解决方案变换集合(在这种情况下-列名的数组)到别的东西(在这种情况下-它们的最大值)。而是使用map
-,然后将结果传递给agg
:
import spark.implicits._
import functions._
val df = Seq((1,3), (3, 1), (2, 2)).toDF("a", "b")
// map columns into columns representing their maximums
val maxCols: Array[Column] = df.columns.map(max)
// aggregate all at once (have to separate first from rest due to agg's signature):
val row: Row = df.agg(maxCols.head, maxCols.tail: _*).head
编辑:正如@ user8371915提醒我们的那样,有一个简短得多的版本:
val row: Row = df.groupBy().max().head
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句