【问题标题】:how to find max value from multiple columns in dataframe in spark [duplicate]如何从spark中数据框中的多列中找到最大值[重复]
【发布时间】:2019-03-05 11:16:16
【问题描述】:

我已将 spark 数据框输入为

sample A B C  D
1      1 3 5  7
2      6 8 10 9
3      6 7 8  1

我需要在作为主题标记的 A、B、C、D 列中找到最大值。 我需要创建一个以 max_marks 作为新列的新数据框。

sample A B C  D  max_marks
  1    1 3 5  7   7
  2    6 8 10 9   10
  3    6 7 8  1   8

我已经使用 scala as 完成了这项工作

val df = df.columns.toSeq
val df1=df.foldLeft(df){(df,colName)=> df.withColumn("max_sub",max((colName)))
df.show()

我收到一条错误消息

"main" org.apache.spark.sql.AnalysisException: 分组表达式序列为空 这个数据框有大约 100 列,所以如何迭代这个数据框 迭代数据框会很有帮助,因为必须找出平均值的列大约是 100 列数据框中的 10 列,大约有 10000 条记录 我希望动态传递列而不手动给出列名,这意味着循环我选择的列并执行任何数学运算

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    有很多方法可以实现这一点,其中一种方法是使用地图。

    简单的伪代码来做你想做的事(无论如何它不会工作,但我认为这个想法很清楚)

    df = df.withColumn("max_sub", "A")
    df.map({x=> {
        max = "A"
        maxVal = 0
        for col in x{
            if(col != "max_sub" && x.col > maxVal){
                max = col
                maxVal = x.col 
            }
        }
        x.max_sub = max
        x
    })
    

    【讨论】:

    • 感谢您的回复,但除了使用 for 循环还有其他方法吗?
    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 2017-10-11
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2017-06-02
    • 1970-01-01
    相关资源
    最近更新 更多