簡體   English   中英

使用 scala/spark 計算數據幀列中每一行的 z 分數

[英]calculate the z score for each row in the column of a dataframe using scala / spark

我有一個數據框:

val DF = {spark.read.option("header", value = true).option("delimiter", ";").csv(path_file)}

val cord = DF.select("time","longitude", "latitude","speed")

我想計算每行速度列的 z score (x-mean)/std.I 計算平均值和標准偏差:

val std = DF.select(col("speed").cast("double")).as[Double].rdd.stdev()
val mean = DF.select(col("speed").cast("double")).as[Double].rdd.mean()

如何計算每行列速度的 z score 並獲得此結果:

+----------------+----------------+-   
|A               |B               |speed    |   z score      
+----------------+----------------+---------------------+
|17/02/2020 00:06|      -7.1732833|   50    |    z score     

|17/02/2020 00:16|      -7.1732833|   40    |    z score   

|17/02/2020 00:26|      -7.1732833|   30    |    z score

如何為每一行計算它。

執行此操作的最佳方法是:

df.withColumn("z score", col("speed") - mean / std)

其中 mean 和 std 的計算方法如問題所示。

如果這有幫助,請告訴我!!

您可以避免使用 Hive 聚合函數中的窗口函數和STDDEV_POP兩個單獨的 RDD 操作:

val DF = {spark.read.option("header", value = true).option("delimiter", ";").csv(path_file)}

val cord = DF.select($"time",$"longitude", $"latitude",$"speed".cast("double"))

val result = cord
  .withColumn("mean",avg($"speed").over())
  .withColumn("stddev",callUDF("stddev_pop",$"speed").over())
  .withColumn("z-score",($"speed"-$"mean")/$"stddev") 

暫無
暫無

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

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