Spark数据帧计算按行最小值 [英] Spark dataframe calculate the row-wise minimum

查看:92
本文介绍了Spark数据帧计算按行最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将几列的最小值放入单独的列中. (创建min列).该操作非常简单,但我无法为此找到合适的功能:
A B分钟
1 2 1
2 1 1
3 1 1
1 4 1

I'm trying to put the minimum value of a few columns into a separate column. (Creating the min column). The operation is pretty straight forward but I wasn't able to find the right function for that:
A B min
1 2 1
2 1 1
3 1 1
1 4 1

非常感谢您的帮助!

推荐答案

您可以使用如果您具有列名列表:

cols = ['A', 'B']
df.withColumn('min', least(*cols))

类似地在 Scala 中:

import org.apache.spark.sql.functions.least
df.withColumn("min", least($"A", $"B")).show
+---+---+---+
|  A|  B|min|
+---+---+---+
|  1|  2|  1|
|  2|  1|  1|
|  3|  1|  1|
|  1|  4|  1|
+---+---+---+

如果列存储在Seq中:

If the columns are stored in a Seq:

val cols = Seq("A", "B")    
df.withColumn("min", least(cols.head, cols.tail: _*))

这篇关于Spark数据帧计算按行最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆