我想根据特定的条件从一个数组中获取最大值,请使用spark scala。
我们有列“a”和列“B”,我想得到每列的最大值,但条件是:if column“a”contains 1,then 1,otherwise max(“a”)max(“B”)有一个重复:
df : res:
+---+---+ +------+------+
| a| b| | maxA| maxB|
+---+---+ +------+------+
| 1| 4| | 1| 5|
| 4| 3| +------+------+
| 6| 5|
| 8| 1|
+---+---+
df : res:
+---+---+ +------+------+
| a| b| | maxA| maxB|
+---+---+ +------+------+
| 0| 4| | 8| 5|
| 4| 3| +------+------+
| 6| 5|
| 8| 1|
+---+---+
我试过这个,但没有工作:
val res = df.agg(max(
when(col("a").contains(1),lit(1))
.otherwise(col("a")))
.as("maxA")
,max("b").as("maxB")
)
我需要把我的条件写在AGG MAX函数里面,而不是外面。
2条答案
按热度按时间kse8i1jr1#
为什么你的方法行不通
让我们看看
when(col("a").contains(1), lit(.otherwise(col("a"))
的输出:如您所见,输出列是相同的。所以基本上,它什么都不做。
如何做你想做的事
如果你只想在一个
.agg
中做这件事,那么使用默认的spark聚合函数是不可能的。好消息是,我们可以实现自定义聚合函数(查看this):就是这样!
如何更有意义地去做
定义一个自定义聚合似乎是非常不必要的。就这样做:
bool_or
是一个聚合函数,通过给定列的所有元素计算布尔逻辑或。在这种情况下,如果a
列中只有一个元素等于1
,则oneFound
将是True
。要使其为False
,您需要列a
的所有值都不同于1
(只有一个true
会使孔表达式的计算结果为true
)。最后,根据oneFound
的值选择1
或maxA
。aurhwmvo2#