簡體   English   中英

通過忽略列中的 0 值來計算平均值

[英]calculate the average by ignoring the 0 values in column

輸入:

item   loc    month   year     qty    
watch  delhi   1       2020     10    
watch  delhi   2       2020     0     
watch  delhi   3       2020     20    
watch  delhi   4       2020     30    
watch  delhi   5       2020     40    
watch  delhi   6       2020     50 

輸出:

item   loc    month   year     qty    avg
watch  delhi   1       2020     10    0
watch  delhi   2       2020     0     10
watch  delhi   3       2020     20    10
watch  delhi   4       2020     30    20
watch  delhi   5       2020     40    25
watch  delhi   6       2020     50    35

我們需要計算前兩個月的平均值......但是在計算平均值時需要一個條件......我們不需要考慮qty = 0而計算平均值.....

例如:對於第 3 個月,理想情況下平均值應為 10+0/2=5....但由於我們需要忽略數量 = 0...所以對於第 3 個月,平均值將為 10/1=10.. ..

提前致謝

在 SQL 中,您可以使用帶有窗口框架說明符的窗口函數:

select t.*,
       coalesce(avg(nullif(qty, 0)) over (partition by item, loc
                                          order by month
                                          rows between 2 preceding and 1 preceding
                                         ),
                0) as qty_avg
from t;

從火花中,

val w = Window.partitionBy("item","loc").orderBy("month").rangeBetween(-2, -1)
df.withColumn("month", 'month.cast("int"))
  .withColumn("avg", avg(when('qty =!= lit(0), 'qty)).over(w)).show()

+-----+-----+-----+----+---+----+
| item|  loc|month|year|qty| avg|
+-----+-----+-----+----+---+----+
|watch|delhi|    1|2020| 10| 0.0|
|watch|delhi|    2|2020|  0|10.0|
|watch|delhi|    3|2020| 20|10.0|
|watch|delhi|    4|2020| 30|20.0|
|watch|delhi|    5|2020| 40|25.0|
|watch|delhi|    6|2020| 50|35.0|
+-----+-----+-----+----+---+----+

可以使用滯后函數和WindowFrame在 spark 中完成

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.IntegerType



df.withColumn("month", col("month").cast(IntegerType))
.withColumn("avg", when(lag("qty", 2, 0).over(w) =!= lit(0) && lag("qty", 1, 0).over(w) =!= lit(0),
(lag("qty", 2, 0).over(w) + lag("qty", 1, 0).over(w)).divide(lit(2)))
.when(lag("qty", 1, 0).over(w) =!= lit(0),lag("qty", 1, 0).over(w)).otherwise(lag("qty", 2, 0)
.over(w))).show()

輸出 :

+-----+-----+-----+----+---+----+
| item|  loc|month|year|qty| avg|
+-----+-----+-----+----+---+----+
|watch|delhi|    1|2020| 10|   0|
|watch|delhi|    2|2020|  0|  10|
|watch|delhi|    3|2020| 20|  10|
|watch|delhi|    4|2020| 30|  20|
|watch|delhi|    5|2020| 40|25.0|
|watch|delhi|    6|2020| 50|35.0|
+-----+-----+-----+----+---+----+

我認為這是一個有條件的 indow 平均值:

select 
    t.*,
    coalesce(avg(nullif(qty, 0)) over(partition by item, loc order by month), 0) qty_avg
from mytable t

nullif()0值產生null - 然后avg()忽略。 我用coalesce()包裹了整個窗口平均值,因為當只有null值時你似乎想要0

暫無
暫無

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

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