我正在尝试将几列的最小值放入单独的列中。 (创建min
列)。该操作非常简单,但我无法为此找到合适的功能:
A B分钟
1 2 1
2 1 1
3 1 1
1 4 1
非常感谢您的帮助!
答案 0 :(得分:4)
您可以在 pyspark 中使用least
函数:
from pyspark.sql.functions import least
df.withColumn('min', least('A', 'B')).show()
#+---+---+---+
#| 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中:
val cols = Seq("A", "B")
df.withColumn("min", least(cols.head, cols.tail: _*))