在 Spark 中分组和标准化 [英] Group By and standardize in spark
本文介绍了在 Spark 中分组和标准化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框:
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()
我想标准化每个键的数据框,不标准化整个列向量.
I want to standardize the dataframe for each key and NOT standardize the whole column vector.
因此对于以下示例,输出将是:
So for the following example the output would be:
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
然后我会对每个组的每个值进行标准化
And then I would get each value standardized per group
我怎样才能在 spark 中做到这一点?
How can I do that in spark?
谢谢
推荐答案
With 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|
+---+----+----+
这篇关于在 Spark 中分组和标准化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文