分组并标准化火花

时间:2017-11-12 15:47:09

标签: python apache-spark pyspark pyspark-sql

我有以下数据框:

enter image description here

a = 1: 
  Column: b
  (2 - 2) / 0.0
  (2 - 2) / 0.0
  (2 - 2) / 0.0
  Column: c
  (3 - 2) / 1.0
  (1 - 2) / 1.0
  (2 - 2) / 1.0

我想标准化每个键的数据帧, NOT 标准化整个列向量。

因此,对于以下示例,输出将为:

<result>Hello World</result>

然后我会得到每组标准化的每个值

我怎么能在火花中做到这一点?

由于

1 个答案:

答案 0 :(得分:1)

使用Spark DataFrame

sdf = spark.createDataFrame(df)

进口:

from pyspark.sql.functions import *
from pyspark.sql.window import Window

def z_score(c, w):
    return (col(c) - mean(c).over(w)) / stddev(c).over(w)

窗口:

w = Window.partitionBy("a")

解决方案:

sdf.select("a", z_score("b", w).alias("a"), z_score("c", w).alias("b")).show()
+---+----+----+                                                                 
|  a|   a|   b|
+---+----+----+
|  1|null| 1.0|
|  1|null|-1.0|
|  1|null| 0.0|
|  2|-1.0|null|
|  2| 0.0|null|
|  2| 1.0|null|
+---+----+----+