Normalize values of multiple columns in Spark DataFrame, using only DataFrame API

前提是你 提交于 2020-01-14 17:15:29

问题


I am trying to normalize the values of multiple columns in a spark dataframe, by subtracting the mean and dividing by the stddev of each column. Here's the code I have so far:

from pyspark.sql import Row
from pyspark.sql.functions import stddev_pop, avg

df = spark.createDataFrame([Row(A=1, B=6), Row(A=2, B=7), Row(A=3, B=8),
                            Row(A=4, B=9), Row(A=5, B=10)])

exprs = [x - (avg(x)) / stddev_pop(x) for x in df.columns]    
df.select(exprs).show() 

Which gives me the result:

+------------------------------+------------------------------+
|(A - (avg(A) / stddev_pop(A)))|(B - (avg(B) / stddev_pop(B)))|
+------------------------------+------------------------------+
|                          null|                          null|
+------------------------------+------------------------------+

Where I'm hoping for:

+------------------------------+------------------------------+
|(A - (avg(A) / stddev_pop(A)))|(B - (avg(B) / stddev_pop(B)))|
+------------------------------+------------------------------+
|                  -1.414213562|                  -1.414213562|
|                  -0.707106781|                  -0.707106781|
|                             0|                             0|
|                   0.707106781|                   0.707106781|
|                   1.414213562|                   1.414213562|
+------------------------------+------------------------------+

I believe I can do this with the StandardScaler class from mllib, but I'd prefer to do this using only the dataframe API if possible - if only as a learning exercise.


回答1:


With thanks to the answer here, I came up with this:

from pyspark.sql.functions import stddev_pop, avg, broadcast

cols = df.columns    
stats = (df.groupBy().agg(
        *([stddev_pop(x).alias(x + '_stddev') for x in cols] + 
          [avg(x).alias(x + '_avg') for x in cols])))

df = df.join(broadcast(stats))

exprs = [(df[x] - df[x + '_avg']) / df[x + '_stddev'] for x in cols]
df.select(exprs).show()

+------------------------+------------------------+
|((A - A_avg) / A_stddev)|((B - B_avg) / B_stddev)|
+------------------------+------------------------+
|      -1.414213562373095|      -1.414213562373095|
|     -0.7071067811865475|     -0.7071067811865475|
|                     0.0|                     0.0|
|      0.7071067811865475|      0.7071067811865475|
|       1.414213562373095|       1.414213562373095|
+------------------------+------------------------+


来源:https://stackoverflow.com/questions/39993879/normalize-values-of-multiple-columns-in-spark-dataframe-using-only-dataframe-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!