【问题标题】:Dataframe: how to groupBy/count then order by count in Scala数据框:如何在 Scala 中分组/计数然后按计数排序
【发布时间】:2018-08-07 11:14:14
【问题描述】:

我有一个包含数千行的数据框,我正在寻找的是分组并计算一列,然后按输出排序:我所做的事情看起来像:

import org.apache.spark.sql.hive.HiveContext
import sqlContext.implicits._


val objHive = new HiveContext(sc)
val df = objHive.sql("select * from db.tb")
val df_count=df.groupBy("id").count().collect()
df_count.sort($"count".asc).show()

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    您可以使用sortorderBy,如下所示

    val df_count = df.groupBy("id").count()
    
    df_count.sort(desc("count")).show(false)
    
    df_count.orderBy($"count".desc).show(false)
    

    不要使用collect(),因为它会将数据作为Array 提供给驱动程序。

    希望这会有所帮助!

    【讨论】:

    • 我改用了这个:df.groupBy("id").count().orderBy($"count".desc).show() 仅一行
    【解决方案2】:
    //import the SparkSession which is the entry point for spark underlying API to access
     import org.apache.spark.sql.SparkSession
     import org.apache.spark.sql.functions._
    
     val pathOfFile="f:/alarms_files/"
    //create session and hold it in spark variable
    val spark=SparkSession.builder().appName("myApp").getOrCreate()
    //read the file below API will return DataFrame of Row
    var df=spark.read.format("csv").option("header","true").option("delimiter", "\t").load("file://"+pathOfFile+"db.tab")
    //groupBY id column and take count of the column and order it by count of the column
        df=df.groupBy(df("id")).agg(count("*").as("columnCount")).orderBy("columnCount")
    //for projecting the dataFrame it will show only top 20 records
        df.show
    //for projecting more than 20 records  eg:
        df.show(50)
    

    【讨论】:

      猜你喜欢
      • 2015-11-14
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多