SPARK DataFrame:删除组中的MAX值



我的数据如下:

id | val
---------------- 
a1 |  10
a1 |  20
a2 |  5
a2 |  7
a2 |  2

如果我在"id"上分组,我将尝试删除组中具有MAX(val)的行。

结果应该是:

id | val
---------------- 
a1 |  10
a2 |  5
a2 |  2

我使用的是SPARK DataFrame和SQLContext。我需要一些类似的方式:

DataFrame df = sqlContext.sql("SELECT * FROM jsontable WHERE (id, val) NOT IN (SELECT is,MAX(val) from jsontable GROUP BY id)");

我该怎么做?

您可以使用数据帧操作和窗口函数来实现这一点。假设数据帧df1:中有您的数据

import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions.Window
val maxOnWindow = max(col("val")).over(Window.partitionBy(col("id")))
val df2 = df1
  .withColumn("max", maxOnWindow)
  .where(col("val") < col("max"))
  .select("id", "val")

在Java中,等价物类似于:

import org.apache.spark.sql.functions.Window;
import static org.apache.spark.sql.functions.*;
Column maxOnWindow = max(col("val")).over(Window.partitionBy("id"));
DataFrame df2 = df1
    .withColumn("max", maxOnWindow)
    .where(col("val").lt(col("max")))
    .select("id", "val");

下面是一篇关于窗口函数的好文章:https://databricks.com/blog/2015/07/15/introducing-window-functions-in-spark-sql.html

下面是Mario的scala代码的Java实现:

DataFrame df = sqlContext.read().json(input);
DataFrame dfMaxRaw = df.groupBy("id").max("val");
DataFrame dfMax = dfMaxRaw.select(
    dfMaxRaw.col("id").as("max_id"), dfMaxRaw.col("max(val)").as("max_val")
);
DataFrame combineMaxWithData = df.join(dfMax, df.col("id")
    .equalTo(dfMax.col("max_id")));
DataFrame finalResult = combineMaxWithData.filter(
    combineMaxWithData.col("id").equalTo(combineMaxWithData.col("max_id"))
        .and(combineMaxWithData.col("val").notEqual(combineMaxWithData.col("max_val"))) 
);

以下是如何使用RDD和一种更具Scala风格的方法来实现这一点:

// Let's first get the data in key-value pair format
val data = sc.makeRDD( Seq( ("a",20), ("a", 1), ("a",8), ("b",3), ("b",10), ("b",9) ) )
// Next let's find the max value from each group
val maxGroups = data.reduceByKey( Math.max(_,_) )
// We join the max in the group with the original data
val combineMaxWithData = maxGroups.join(data)
// Finally we filter out the values that agree with the max
val finalResults = combineMaxWithData.filter{ case (gid, (max,curVal)) => max != curVal }.map{ case (gid, (max,curVal)) => (gid,curVal) }

println( finalResults.collect.toList )
>List((a,1), (a,8), (b,3), (b,9))

相关内容

  • 没有找到相关文章

最新更新