apache-spark - Spark数据框计算行最小值

标签 apache-spark apache-spark-sql

<分区>

我试图将几列的最小值放入单独的列中。 (创建 min 列)。该操作非常简单,但我找不到合适的函数:
A B 分
1 2 1
2 1 1
3 1 1
1 4 1

非常感谢您的帮助!

最佳答案

您可以使用 least函数,在 pyspark 中:

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: _*))

关于apache-spark - Spark数据框计算行最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51974475/

相关文章:

hadoop - 终止 aws 中的 Spark 步骤

java - Spark SQL : Window function lag until a condition met

java - 使用 Java 比较 Spark 中的两个数据帧?

apache-spark - Spark 随机删除行

hadoop - 具有 gzip 格式的大文本文件的 Spark 作业

python-3.x - PySpark-如何使用 Pyspark 计算每个字段的最小值、最大值?

java - 使用 Apache Spark 的 Hibernate 持久化导致进程阻塞

sql - Spark SQL 超时

apache-spark-sql - 在 Parquet 数据框中按时间戳进行分区的最佳方法

apache-spark - Spark ALS 推荐系统预测值大于 1