python - Spark 中的分组和标准化

标签 python apache-spark pyspark apache-spark-sql

我有以下数据框:

enter image description here

import pandas as pd
import numpy as np
df = pd.DataFrame([[1,2,3],[1,2,1],[1,2,2],[2,2,2],[2,3,2],[2,4,2]],columns=["a","b","c"])
df = df.set_index("a")
df.groupby("a").mean()
df.groupby("a").std()

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

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

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

然后我会对每个组的每个值进行标准化

如何在 Spark 中做到这一点?

谢谢

最佳答案

使用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|
+---+----+----+

关于python - Spark 中的分组和标准化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47250721/

相关文章:

python - PySpark使用RDD和json.load解析Json

python - 每次 Spark 窗口函数

python - centos7.3上无法安装mysqlclient

python - TF2.6 : ValueError: Model cannot be saved because the input shapes have not been set

java - Apache Spark 使用 Java 加入示例

python - 在 PySpark 中应用自定义函数时使用外部模块

scala - org.apache.spark.ml.feature.Tokenizer 中的 NullPointerException

python - 可以在python中使用mediapipe进行人脸识别

python - 在 python 中使用用户输入(input)向类添加新对象

python - 在 Spark 数据框中拆分列