簡體   English   中英

如何使用火花/標量獲取RDD中當前位置前面的平均值

[英]How to get the avg values in front of the current position in a RDD with spark/scala

我有一個RDD ,我想在當前位置前方的平均值(包括當前位置)在RDD例如:

inputRDD:
1,  2,   3,  4,   5,  6,   7,  8

output:
1,  1.5, 2,  2.5, 3,  3.5, 4,  4.5

這是我的嘗試:

val rdd=sc.parallelize(List(1,2,3,4,5,6,7,8),4)
    var sum=0.0
    var index=0.0
    val partition=rdd.getNumPartitions
    rdd.zipWithIndex().collect().foreach(println)
    rdd.zipWithIndex().sortBy(x=>{x._2},true,1).mapPartitions(ite=>{
      var result=new ArrayBuffer[Tuple2[Double,Long]]()
      while (ite.hasNext){
        val iteNext=ite.next()
        sum+=iteNext._1
        index+=1
        var avg:Double=sum/index
        result.append((avg,iteNext._2))
      }
      result.toIterator
    }).sortBy(x=>{x._2},true,partition).map(x=>{x._1}).collect().foreach(println)

我必須repartition為1,然后使用數組進行計算,所以效率很低。

有沒有在4個分區中不使用數組的更清潔的解決方案?

一個更簡單的解決方案是使用Spark-SQL。 在這里,我正在計算每一行的移動平均值

val df = sc.parallelize(List(1,2,3,4,5,6,7,8)).toDF("col1")

df.createOrReplaceTempView("table1")

val result = spark.sql("""SELECT col1, sum(col1) over(order by col1 asc)/row_number() over(order by col1 asc) as avg FROM table1""")

或者,如果您想使用DataFrames API,也可以使用。

import org.apache.spark.sql.expressions._
val result = df
 .withColumn("csum", sum($"col1").over(Window.orderBy($"col1")))
 .withColumn("rownum", row_number().over(Window.orderBy($"col1")))
 .withColumn("avg", $"csum"/$"rownum")
 .select("col1","avg")

輸出

result.show()

+----+---+
|col1|avg|
+----+---+
|   1|1.0|
|   2|1.5|
|   3|2.0|
|   4|2.5|
|   5|3.0|
|   6|3.5|
|   7|4.0|
|   8|4.5|
+----+---+

抱歉,我沒有使用Scala,希望您能閱讀它

df = spark.createDataFrame(map(lambda x: (x,), range(1, 9)), ['val'])
df = df.withColumn('spec_avg',
                   f.avg('val').over(Window().orderBy('val').rowsBetween(start=Window.unboundedPreceding, end=0)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM